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?

Peppermintology
  • 9,343
  • 3
  • 27
  • 51
Rizal Yogi Pratama
  • 117
  • 1
  • 1
  • 9

2 Answers2

2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
yhiamdan
  • 113
  • 1
  • 7
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}`
   }
}
apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • 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 – Rizal Yogi Pratama Jun 03 '21 at 08:20
  • 2
    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 – apokryfos Jun 03 '21 at 08:35