I have an application that has the following setup:
Laravel
Host: appname.local:8000
Environment variables:
- SESSION_DRIVER=database
- SESSION_LIFETIME=480
- SESSION_CONNECTION=mysql
- SESSION_DOMAIN=.appname.local
- SESSION_SECURE_COOKIE=false
- SESSION_COOKIE=appnameapi_session
- SANCTUM_STATEFUL_DOMAINS=’.appname.local,localhost,127.0.0.1′
Angular
Host: appname.local:4200
What works at the moment:
- I can call Sanctum’s csrf-cookie endpoint which sets the CSRF token in my browser.
- I then can call my API’s login endpoint to authenticate the user in my Laravel app using Auth::attempt(). This create a new entry in the sessions table as seen below
Angular methods to get token and authenticate user
Session database entry after successful authentication
What does not work:
Subsequent requests to routes that are protected by the following middleware: auth:sanctum all result in unauthenticated responses. The HTTP requests never make it to my controllers.
But I can see in the developer’s console that the cookies are being sent. So I don’t understand why Sanctum isn’t picking up the auth
I’ve followed several tutorials and I can’t seem to understand why Laravel’s Authenticate middleware is unable to see that I’ve already authenticated my user.
Does anyone know what I could be doing wrong?
Advertisement
Answer
The answers provided by @agm1984 and @Eden Webstudio were quite useful. However, they did not solve my issue.
After additional debugging, I noticed that sanctum’s guard logic looks for a guard in
config/sanctum.php
. Its default value is web. My default guard for the protected routes is the api guard which is the guard that I used during the authentication process.
After setting the guard key in config/sanctum.php with ‘api’ the authentication seems to be working smoothly. To be honest, I can’t remember why I decided to the session driver for my api guard.
config/auth.php