laravel-sanctum-example
laravel-sanctum-example copied to clipboard
Unauthorized error in /api/user
Hello,
I have set up your example application according to the readme and when I log in using my credentials the request succeeds but the following request to /api/user
ends with 401 Unauthorized with the {"message":"Unauthenticated."}
body.
I have tried your example because I'm facing the same issue in my app where I try to use Sanctum.
Have you seen this issue before?
From what I found out when debugging the authentication process in Laravel I see that the session seems not to be initialized on the /api/user
request, therefore Laravel doesn't find the session entry identified by the cookie sent with the request and fails with 401 Unauthorized.
I faced same problem can you please provide any help on it.
Thanks
You need in the header, token authorization in Apis/Api.js commend save response of login in localStorage and add in header
Login.vue function
login() {
User.login(this.form)
.then((response) => {
this.$root.$emit("login", true);
/*
Add in localStorage response of Login, token type and token access
*/
localStorage.setItem("auth", JSON.stringify({
'tokenType': response.data.token_type,
'accessToken': response.data.access_token
}));
this.$router.push({ name: "Dashboard" });
})
.catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors;
}
});
}
apis/Api.js
import axios from "axios";
/*
Check if have data in localStorage, because login not required bearer auth,
and if you try to access to authValues.tokenType is undefined
*/
let authValues = JSON.parse(localStorage.getItem("auth"));
let token = authValues ? `${authValues.tokenType} ${authValues.accessToken}` : null;
let Api = axios.create({
baseURL: "http://localhost:8000/api",
headers: { 'Authorization': token }
});
Api.defaults.withCredentials = true;
export default Api;
change your api middleware to web middleware in RouteServiceProvider in API routes