1

I just trying to makes my auth flow more secure using a cookie on Laravel 5.7

Here my code

/**
 * auth logic
 */
return response()->json(["status" => "logged in"], 200)->cookie('token', $token, $lifetime);

Then the cookie will be saved on the browser and will be used on every request.

On header with Axios

"cookie":"token={token}"

And I validate the auth using default middleware

Route::group(['middleware' => ['auth:api']])

But the auth:api did not recognize it, I can make custom middleware by manually detect the cookie, but I can't use the auth()->user() function on it. Is there any solution for this?

2
  • if you want to use cookie, just use default auth middleware instead of auth:api Commented Jun 3, 2021 at 7:40
  • @MuhammadDyasYaskur okay lemme try Commented Jun 3, 2021 at 8:20

2 Answers 2

3

From your sample code I believe your app is built on a stateless architecture where you have your JavaScript client and laravel api. Now I am a bit confused as to why you do not want the client storing the token, if you just want to escape cross site scripting vulnerability (XSS) then you have to prepare to deal with cross site request forgery (CSRF) if you store the token in the browsers cookie. Regarding the middleware not being able to find the token, by default the middleware is configured to lookup tokens in the request header (specifically the Authorization header) so if you decide to store it in the cookie, you have to find a way to change the token lookup in the api middleware which unfortunately I have not done before in laravel.

Sign up to request clarification or add additional context in comments.

Comments

1

APIs don't generally store and send cookies. Therefore the api token authentication guard will not look for the token in a cookie. There are multiple options you can send it as though the easiest one in axios:

{
   headers: {
     Authorization: `Bearer ${token}`
   }
}

2 Comments

currently, i'm using this, but i don't want the frontend side to store the token but if we used cookie, the browser would be auto save the cookie
You really should not use API routes for browser interactions. If using the browser and relying on cookies then use the session and the web auth guard

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.