So you can make sure that the JWT token is available everywhere for Axios or even any external interface.
The most common way is to store the token in a cookie or in the browser web storage ( localStorage / sessionStorage )
The difference between localStorage and sessionStorage is that the data stored in localStorage is saved through browser sessions, sessionStorage is cleared when the page session ends.
The general consensus is that cookies are a bit more secure as they have a smaller attack vector, although none of them are completely secure. If you want to go deeper, you can start by reading this article.
To get more specific information about your problem, first you want to set up a marker store using one of the methods described above, the recommended method is cookies, you can find examples of how to do this using pure Javascript.
Now that you have a marker on each page, you can redirect the user depending on what you like. Although I would suggest that instead of using your own JWT authentication middleware, you can use the one provided by the JWT library: jwt.auth .
This middleware will automatically respond with error codes, if something is wrong with the token, if any, it will return one of the following HTTP responses:
token_not_providedtoken_expiredtoken_invaliduser_not_found
If one of these answers is returned (or if the request status code is 400), you can simply use the interface to redirect the user back to your pre-authorization routes.
When logging in after saving a cookie in a cookie, use the interface to redirect to post-out routes.
I know that you said that you want to keep the redirection logic in the backend, but it does not make sense when, for example, you call the API when you log in, you cannot return the marker, they cause redirection at the same time as the backend.
UPDATE
A very simple example of how you can only authenticate with security and still get the token for the API. Borrowing from the redirect example from @Ohgodwhy, you can put the following into your RedirectIfAuthenticated middleware.
public function handle($request, Closure $next, $guard = null) if (Auth::guard($guard)->check()) { if ((\Cookie::get('access_token') == null)) { $cookie = \Cookie::make( 'access_token', \JWTAuth::fromUser(Auth::user()), config('session.lifetime'), null, $request->refeerer, false, // to make the cookie available in javascript false // to make the cookie available in javascript ); return redirect('/home')->cookie($cookie); } else { return redirect('/home'); } } return $next($request); }
Just make sure your $redirectTo in app/Http/Controllers/Auth/LoginController.php set to a path that implements the RedirectIfAuthenticated middleware.