1

I have Laravel Sanctum set up for API and Web routes.

My guarded Web routes are defined like so:

Route::get('/my-account', [UserController::class, 'getMyAccount'])
    ->middleware('auth:sanctum');

As for how I'm storing the token, on login and register requests, I saw online somewhere to return the token as a HTTP cookie like so:

UserController.php

public function create(CreateUserRequest $request): JsonResponse
{
    // The userService->create() code works and has been tested.
    // It creates a user and Sanctum token, and returns them.
    // No need to show it as not part of the issue and just gets convoluted
    $response = $this->userService->create($request->validated());
    $cookie = cookie('BEARER-TOKEN', $response['token'], 60);

    return response()
        ->json($response)
        ->cookie($cookie);
}

Here's the API route for that function:

Route::post('/user', [UserController::class, 'create']);

Though when I try to access /my-account after creating it. Sanctum fails validation, and redirects me to my login route.

Am I doing something wrong?

UndercoverCoder
  • 953
  • 3
  • 13
  • 28
  • Check if you are sending tokens when requesting the page. – Abdulla Nilam Jul 29 '23 at 11:16
  • @AbdullaNilam - Just checked, it's definitely sent as a Request Header on page load – UndercoverCoder Jul 29 '23 at 11:25
  • You must send as Authorization: Bearer . Request with this header fail? – Maksim Jul 29 '23 at 12:25
  • @Maksim - How will the front-end make get the token to assign that header? – UndercoverCoder Jul 29 '23 at 13:04
  • We dont know what u use for frontend - Vue, blade, etc. Than cannot answer. Follow documentation, you can send header as Bearer on every request or utilize session guard. – Maksim Jul 29 '23 at 13:50
  • @Maksim - My bad, I use Blade with vanilla Javascript to make request. I can send return the token, store it in a browser cookie or local storage and use that, but I've been told that's not secure. So I now set it as a HTTP Cookie from the server. Which is added in every request. – UndercoverCoder Jul 29 '23 at 14:40

0 Answers0