5 months ago

Laravel Passport - Store token in cookies

Posted 5 months ago by tomspeak

I am using Laravel 5.8 and Passport 7.3.

I am using Passport with, strictly. I am not using any of the oAuth features at all.

The set up I want is to make an API request from an SPA from to my Laravel instance on using Cookies.

I have managed to get this working (but not in the way I want), to prove my set up is working end to end.

When you hit api/auth/login, I authenticate the User and return a cookie that contains:

$token = $user->createToken('MyApp')->accessToken;

I am using NextJS for the front-end, which allows me to get the Cookie from the Headers sent to my Express server that is being used to run NextJS, I then pass this to my React Component that sends it off in the Authorization: Bearer header.

Using this method I can pass `->middleware('auth:api').

Now, I want to change from Authorization: Bearer to just passing the secure, httpOnly cookies they already have stored, so I can make API calls from the client.

The docs talked about passing the Authorization: Bearer, but do not mention cookies.

The docs show how to pass the token via Cookies, but my API is only a completely server, so my web routes are never used as the API is headless.

How do I make it so my API routes read the Cookies sent, and have the authorization check against that, instead of Authorization: Bearer when using ->middleware('auth:api'), Auth::logout() etc?

Please sign in or create an account to participate in this conversation.