R
R
Romi2021-05-13 11:03:23
Laravel
Romi, 2021-05-13 11:03:23

How to disable redirect to /login for guests for route with ->middleware('auth:api')?

In routes:

Route::any('/test, [TestController::class, 'main'])->middleware('auth:api');

and if the token is wrong, it will redirect to /login

, but I don’t need this for the API, of course, I just need it to give a response from main()

found in app/Http/Middleware/Authenticate.php
protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }

but even if it's just commented out, it still redirects...

In terms of meaning, I understand that if I send 'application/json' in the headers, then everything will be fine, but I don't like it when my arms are twisted like that)))

Where Can this redirect be cancelled?

Thanks in advance for your reply.

// in google and stack, anything except the answer to the question posed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
James026, 2021-05-17
@romicohen

1) in the app/Exceptions/Handler.php file, override the unauthenticated method from vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php
, that is, do something like this

protected function unauthenticated($request, AuthenticationException $exception)
{
    return response()->json(['message' => $exception->getMessage()], 401)
}

but it will work globally
2) make your Middleware like vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php
only throw your own exp, and in the app/Exceptions/Handler.php file override the parent render method to handle your custom error for example:
public function render($request, Throwable $e)
{
    if ($e instanceof CustomAuthenticationException) {
        return response()->json(['message' => $e->getMessage()], 401);
    }
    return parent::render($request, $e); 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question