I have an rest api that, depending on whether the user is authorized or not, issues different products /api/products. This api for a mobile application, I carry out authorization through a bearer token with Sanctum. To process requests from any users and, depending on whether there is a token or not, display goods.
My custom middleware for api
public function handle(Request $request, Closure $next): Response
{
if ( $request->bearerToken() && Auth::guard('sanctum')->user() )
Auth::setUser( Auth::guard('sanctum')->user() );
return $next($request);
}
Next, it took not only api but also a website that will use this api, which is intended for a mobile application. Decided to use the usual php approach using vue components. Its Breeze & Blade with Fortify and Vue. As far as I understand, if the user is authorized through the website, cookies with authorization come to him and they must be applied to Ajax requests.
My axios request from vue component to /api/products.
If the user is authorized through the website, then a cookie is applied and sent
const instance = axios.create({
timeout: 2000,
//My cookie included
withCredentials: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials' : true
},
//With token works. Middleware understands that the user is authorized
//headers: {'Authorization': 'Bearer '+'1|XedL48l1TU5KomRxix6xFrsm0v7jw5eTbHzfpoGC'}
});
instance
.post("/api/products",
{
data: example_data,
}, )
.then(response => {
console.log(response.data)
});
The problem is that the middleware does not understand the cookies that come with the axios request. Middleware can't figure out if I'm authorized or not through the cookies attached to requests. It understands only the token in header, it works with the token.The documentation says that the Sanctum middleware understands the cookies that are attached to the request, but I do not use the middleware sanctum. Is it possible to implement it somehow, so that the authorized user's cookies would be understood by my custom middleware and not just the token?