Have you correctly configured axios and the cors configuration file ?
Allow web authenticated users to access api endpoints.
Hello everyone! I want to authenticate users using the web route and allow access to the api routes that are protected with sanctum middleware 'auth:sanctum'. To achieve this, whenever a user is authenticated, I return the view and attached sanctum token in the cookie.
public function login(Request $request) {
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'success' => false,
'message' => 'Login failed'
], Response::HTTP_UNAUTHORIZED);
}
$token = auth()->user()->createToken('token')->plainTextToken;
$expiration = 60 * 24; // 24hrs
$cookie = cookie('token', $token, $expiration);
return response()->json([
'success' => true,
'message' => 'Login successful'
], Response::HTTP_ACCEPTED)->withCookie($cookie);
}
The purpose of this is to omit the frontend to manually set the 'Authorization' in the header like so:
const response = await fetch('/api/user', {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
The problem is although I have set the 'Authorization' header in the middleware, it still returns 401 when I try to access the api route. I tried to die dump the $token and it has the correct sanctum token. I am able to access the api routes when I use postman or insomnia but it doesn't work in the web when I try to send http request via javascript fetch api.
Here is my middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Closure;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
public function handle($request, Closure $next, ...$guards)
{
$token = $request->cookie('token');
if (!is_null($token)) $request->headers->set('Authorization', 'Bearer ' . $token);
$this->authenticate($request, $guards);
return $next($request);
}
}
@rcvioleta But if you use Sanctum as it’s intended to be used then you wouldn’t be storing the token in the first place.
You should only be using API tokens for things like mobile apps. Use cookies for your web app.
Please or to participate in this conversation.