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

ideative's avatar

API returns 302 instead of 401

I'm building an API with Laravel and it seems to work, however as soon as I activate an auth middleware (auth:api) I'm getting unintended responses.

Without getting too much into detail, take for instance the default /api/user route which comes with Laravel 5.4 installation. By default it await auth with its auth:api middleware, but also return 302 instead of 401 (unauthorized).

I thought it came from my app/Exceptions/Handler.php file, but its the original one that came with installation. Is there anywhere I can look to personalize auth:api responses ? Any why by default I'm getting 302 (Found) with redirection to Homepage?

0 likes
4 replies
WebKenth's avatar
  • Step 1 find the endpoint probably in your api.php route file
  • Step 2 go to the controller function
  • Step 3 read it and understand why it redirects

Did you follow the steps in Laravel API Authentication

Or are you simply trying to login with the default Auth controller?

ideative's avatar

I switch default auth to Passport (if it is relevant), but at this point I'm not even trying to login with any token. I havent generated any yet. I just want API to return proper error, which should be:

if ($request->expectsJson()) {
    return response()->json(['error' => 'Unauthenticated.'], 401);
 } 

according to Exceptions/Handler.php

The default route (that came with installation):

 Route::middleware('auth:api')->get('/user', function (Request $request) {
     return $request->user();
 });

It just returns current user (if logged in) and I don't believe it has controller associated with it.

oscarteg's avatar

For people seeing this. Don't forget to add the accept header to your request.

2 likes

Please or to participate in this conversation.