laravel-sanctum-example icon indicating copy to clipboard operation
laravel-sanctum-example copied to clipboard

Unauthorized error in /api/user

Open KKSzymanowski opened this issue 4 years ago • 3 comments

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.

KKSzymanowski avatar Jul 10 '20 07:07 KKSzymanowski

I faced same problem can you please provide any help on it.

Thanks

shahid-mushtaq avatar Aug 26 '20 11:08 shahid-mushtaq

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;

dimasx010 avatar Nov 03 '20 13:11 dimasx010

change your api middleware to web middleware in RouteServiceProvider in API routes

rohit-sagar256 avatar Jun 14 '21 10:06 rohit-sagar256