Why does Laravel Fortify send a redirect on an API Request?

287 views Asked by At

I´m using Laravel (10) Fortify (with Sanctum), to authenticate requests to the REST API. It works quite well but I´ve one serious issue and I think it´s simply a configuration problem:

Whenever an API request on a Fortify route fails (e.g. send a login request when the user is already logged in), Laravel (Fortify) tries to redirect the client to a defined route (e.g. home) as would it be a classic web request. However, that should normally not happen, when it´s an API request with "Accept: application/json" header in my understanding. In that case I would expect a http status matching the issue as a response but no redirect header.

2

There are 2 answers

0
Mike On BEST ANSWER

Finally there are two possible solutions:

1. Update RedirectIfAuthenticated middleware as suggested by @Zenix

if(!$request->wantsJson()){
    return redirect(RouteServiceProvider::HOME);
}

2. Setup own API routes for fortify and don´t include the RedirectIfAuthenticated middleware

// Login
// "guest" Middleware (alias for RedirectIfAuthenticated) not enabled on API routes
    // cause it redirects to the login page, which is not what we want for API routes
    $limiter = config('fortify.limiters.login');
    Route::post('/login', [AuthenticatedSessionController::class, 'store'])
      ->middleware(
        [
          //'guest:' . config('fortify.guard'),
          $limiter ? 'throttle:' . $limiter : null
        ]
      );

In my opinion Option 1 is the better way to go cause it resolves the issue on the basis. Thanks for your support!

0
ZeNix On

Fortify by default uses the RedirectIfAuthenticated middleware, you can disable it by commenting the line return redirect(RouteServiceProvider::HOME); or adding a "if" statement:

if(!$request->wantsJson()){
    return redirect(RouteServiceProvider::HOME);
}