Home > Blockchain >  Laravel api bypass auth api for specific ip address
Laravel api bypass auth api for specific ip address

Time:01-06

Below is my laravel 8 api route and middleware that I use

Route::group(['middleware'=>['auth:api', 'StripScript'],'prefix' => 'v1'], function(){
    Route::get('/list', [ListController::class, 'list']);
});

I this I want to bypass middleware 'auth:api' if I get request from specific ip address so user doesn't require to pass token and it should auto login as one specific user.

Note that I want to bypass auth and not to do 'Ip address Whitelist' as I do have whitelist for this I want to totally by pass for one IP address.

CodePudding user response:

It's not good idea, But any way if you want try this...

Go app/Http/Middleware/Authenticate.php

Add && override handle function like below

    public function handle($request, \Closure $next, ...$guards)
    {

        // check $request is coming from where and set a statement ture/false for a $isComingFromDesiredIp;

        if (! $isComingFromDesiredIp) {
            $this->authenticate($request, $guards);
        }

        return $next($request);
    }

CodePudding user response:

This should work:

Route::group(['middleware' => in_array(request()->ip(), $arrayOfTrustedIps) ? ['StripScript'] : ['auth:api', 'StripScript'],'prefix' => 'v1'], function(){
    Route::get('/list', [ListController::class, 'list']);
});

You should also handle the references to the authed user, if there are any (e.g. auth()->user()->id will throw an error).

IMHO you should authenticate the trusted party via a token sent in header, if you have access to the api call code. Managing these kind of exceptions in your code can quickly become cumbersome and will be challenging to understand for everyone (including you).

  • Related