[英]Error 401: Unauthorized on Laravel Sanctum Authentication and Vue
I get a status error code when I try to access the data after logging in. I am getting the XRSF token when someone attempts to log in but can't the user data back.我在登录后尝试访问数据时收到状态错误代码。当有人尝试登录但无法返回用户数据时,我收到了 XRSF 令牌。
Below is my useAuth.js code下面是我的 useAuth.js 代码
import axios from 'axios'
export default function useAuth() {
const login = async (credentials) => {
await axios.get('/sanctum/csrf-cookie') // ! STATUS CODE - 204 - Ok
await axios.post('/login', credentials) // ! STATUS CODE - 200 - Ok
let response = await axios.get('/api/user')
console.log(response) // ! STATUS CODE - 401 - UNATHORIZED
}
return {
login
}
}
My routes/api.php code我的路线/api.php 代码
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
My.env我的.env
SESSION_DRIVER=file
SESSION_LIFETIME=120
SANCTUM_STATEFUL_DOMAINS=localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1
I tried to change SESSION_DRIVER to cookie but brings the same result as file我试图将 SESSION_DRIVER 更改为 cookie,但结果与文件相同
Main App.vue code主 App.vue 代码
<template>
<form v-on:submit.prevent="login(form)">
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" v-model="form.email">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" v-model="form.password">
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</template>
<script setup>
import { reactive } from 'vue'
import useAuth from './auth/useAuth'
const { login } = useAuth()
const form = reactive({
email: '',
password: ''
})
</script>
Anyone with an idea on how I can solve the problem任何对我如何解决问题有想法的人
Thank you谢谢
I think you forget to send your token in Authorization header in this request我认为您忘记在此请求中在授权 header 中发送您的令牌
let response = await axios.get('/api/user')
So you must add your bearer token to authorization header like this:因此,您必须将您的不记名令牌添加到授权 header 中,如下所示:
axios.defaults.headers.common['Authorization'] = `Bearer your_token`;
You also need to tell axios to include cookies when sending requests:您还需要在发送请求时告诉 axios 包括 cookies :
axios.defaults.withCredentials = true;
Also make sure cors.php has support_credentials set to true.还要确保 cors.php 将 support_credentials 设置为 true。
Thought this might help, I did get an answer to this question after much research.认为这可能会有所帮助,经过大量研究,我确实得到了这个问题的答案。 Silly me
傻我
SANCTUM_STATEFUL_DOMAINS=localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1
The above code should be set to the exact domain port.上面的代码应该设置为确切的域端口。
You can check for further assistance on the link below您可以通过以下链接查看更多帮助
Getting 401 unauthorized for Laravel sanctum Laravel sanctum 获得 401 未经授权
MR_AMDEV answer. MR_AMDEV 答案。
Your all welcome欢迎大家
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.