api:auth middleware returning login screen on unauthenticated

Posted 1 year ago by itstrueimryan

I have a route set up in api.php:

Route::get('test', function() {
    dd('test');
})->middleware('auth:api');

I have my app all hooked up with Passport's token system, so I get a token by hitting the endpoint /oauth/token, and then proceed to use that to hit my api endpoints. Works great. However, when a route like the one above is sent an invalid token, instead of getting a 401 Unauthorized error like I should, I'm getting redirected to the login page on my front end.

When I look at what is going on under the hood, I see that it gets to this method in Authenticate.php:

   protected function authenticate(array $guards)
    {
        if (empty($guards)) {
            return $this->auth->authenticate();
        }

        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        throw new AuthenticationException('Unauthenticated.', $guards);
    }

With testing, I've found out that it does indeed reach that bottom exception. Still, I'm getting a login screen in response in Postman so I'm not really sure what's going on. All I'm looking for is a simple 401.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.