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

mstdmstd's avatar

I got 302 code when run api url without tokens

Hello, In laravel 5.5 laravel/passport 4.0 is used for external api and when I try to enter url in browser without any tokens I see that in the browser that 302(found) code is returned. But I expected 401. Any hints why can it be so and where have I to catch it?

I looked to api' block in app/Http/Kernel.php file and reviewed all files in app/Http/Middleware/ and did not any redirects like that.

Any ideas where can I catch these errors or some manual redirecting, which could be made by prior developers?

Thanks!

0 likes
3 replies
drewdan's avatar

You are running this in your browser you said? It sounds to me like it is doing a 302 to redirect it to the login page maybe?

I think you would need to add a middleware to force a content type of application/json.

I think this video might be helpful to understand how the api stuff works in Laravel: https://www.youtube.com/watch?v=2JBh0yk3hn4&feature=youtu.be - albeit this is not using passport, but might help understand what is causing the redirects.

martinbean's avatar

in the browser that 302(found) code is returned. But I expected 401. Any hints why can it be so and where have I to catch it?

@mstdmstd Because you’re running it in the browser. The authentication middleware will be kicking in and by default will show a JSON response if the request is expecting JSON, or redirect to your login route. Hitting a URL in a browser is not a request that expects a JSON response.

If you sent the request using an Accept: application/json header than you would get a JSON response and a 401 status code. So instead, consider writing an actual test instead of just trying to hit URLs in the browser:

$this
    ->postJson('/api/some-uri-that-requires-authentication')
    ->expectStatus(401);
mstdmstd's avatar

I run in postman and got login page with 200 code returned.

I suppose that I need to write middleware to hook unauthorized event and check if url is under ‘/api/’ to return json with 401 code. Has laravel some hooks to make it ? All requests in routes/api.php under auth:api :

Route::group(['prefix' => 'api'], function () {
    Route::group(['prefix' => 'v1'], function () {
        ...
        Route::group(['middleware' => 'auth:api', 'prefix' => 'home'], function () {
            ...
            Route::get('/data', 'DataController@index');

how better to deal it ?

Please or to participate in this conversation.