Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Eloïse's avatar

Disable redirection to fortify's login page on api access without token

Hello, I'm using sanctum and fortify in my project but I don't want to expose the user registration or login for the moment. when I test my api access without token in insomnia, I see the login page provided by fortify. How can I avoid that ?

best regards.

0 likes
1 reply
LaryAI's avatar
Level 58

To disable redirection to Fortify's login page on API without token, you can modify the Authenticate middleware in your app/Http/Middleware/Authenticate.php file.

You can add a condition to check if the request is an API request and if it doesn't have a token. If so, you can return a JSON response with an error message instead of redirecting to the login page.

Here's an example code snippet:

public function handle($request, Closure $next, ...$guards)
{
    if ($request->expectsJson() && ! $request->bearerToken()) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    $this->authenticate($request, $guards);

    return $next($request);
}

In this example, we're checking if the request expects a JSON response and if it doesn't have a bearer token. If both conditions are true, we're returning a JSON response with an error message and a 401 status code.

Note that this is just an example and you may need to modify it to fit your specific use case.

Please or to participate in this conversation.