Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unauthorized error in /api/user #1

Open
KKSzymanowski opened this issue Jul 10, 2020 · 3 comments
Open

Unauthorized error in /api/user #1

KKSzymanowski opened this issue Jul 10, 2020 · 3 comments

Comments

@KKSzymanowski
Copy link

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.

@shahid-mushtaq
Copy link

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

Thanks

@dimasx010
Copy link

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;

@rohit-sagar256
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants