how can i protect laravel api calling from other website

Access-Control-Allow-Origin https://mydomain.com/

 added a new middleware

<?php

namespace App\Http\Middleware;

use Closure;

class VerifyAPIAccess
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (
            !(App::environment('local'))
            && (
                !$request->header('access-token')
                || $request->header('access-token') !== env('APP_API_TOKEN')
            )
        ) {
            return response()->json(['Message' => 'You do not access to this api.'], 403);
        }

        return $next($request);
    }
}

and then added to my route

Route::group([
    'middleware' => [
        VerifyAPIAccess::class,
 	'throttle:60,1'
    ]
], function () {

// list some routes

});

you could also restrict access by adding throttling which would stop someone from hammering your API, with token or not.

There are probably many approaches. A simple but effective one would be sessions. You can save the user in a session. This way you can also count his Api accesses. As soon as they are larger than allowed, you can block their requests. You also write the block in the session. But pay attention to the session duration. It must be long enough.

But the user with bad intentions can get a new session. To avoid this, you can also put his IP on an internal blacklist for a day.

Note: But an open api is always a point of attack.

Things tried:

  • Using passport to protect my routes and then use passport’s CreateFreshApiToken middleware. Protection works fine, unauthorized users are not able to access the routes, however I don’t get laravel_token in my cookies and therefore I can’t get access to that route if I’m not logged in.
  • Use passport’s client credentials grant access. Works fine and the way I want it to work but doesn’t really make sense because if I hardcode the client_secret – anyone can access it and then use it to access protected routes. If I make a proxy-like solution, to call a controller method, which would issue a valid token and thus not exposing client_secret to front-end but then anyone could just call that route which issues the token and it would be pointless once again.

You cannot stop people from trying to access of publicly visible API. You need to secure the API and only respond to those with the proper access privileges. 



Leave a Reply