skip to Main Content

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

Answers


  1. Chosen as 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!


  2. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search