Laravel Sanctum + Vue Auth
Laravel Sanctum + Vue Auth
我有一个使用Laravel Sanctum进行安全保护的API。在前端,我成功地使用sanctum登录,并生成了一个新的bearer token。到目前为止一切顺利,但是我应该如何将token(不使用Vuex)存储到本地存储中,并告诉axios在以后的请求中使用该token?
我的代码如下:
// AuthController.php
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('email', $fields['email'])->first();
$token = $user->createToken('login_token')->plainTextToken;
if (!$user || !Hash::check($fields['password'], $user->password)) {
return response([
'message' => 'Invalid Login Credentials'
], 401);
}
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
// Login.vue
export default {
methods: {
handleLogin() {
axios.get("/sanctum/csrf-cookie").then(response => {
axios.post("/api/login", this.formData).then(response => {
if (response.status === 201) {
this.$router.push({ path: "/" });
}
console.log(response);
});
});
}
},
data: function() {
return {
logo: logo,
formData: {
email: "",
password: ""
}
};
}
};
登录功能正常,返回了预期的结果,但是我不知道如何存储生成的token,并如何将其发送到任何以后的axios请求中。
谢谢。
*** 更新 ***
好的,我弄清楚了如何发送headers,我这样做:
axios
.get("/api/expenses/", {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "6|cnuOY69grhJiZzxEHoU74PapFkkcJeqbf3UiKx8z"
}
})
.then(response => (this.expenses = response.data.data));
现在,唯一剩下的问题是如何将token存储到本地存储中,因为目前为止,我为了测试目的硬编码了token。
Laravel Sanctum + Vue Auth问题的出现原因是在使用axios调用API时没有正确地传递token,导致API请求无法通过验证。为了解决这个问题,我们可以将token存储在本地存储中,并在发送axios请求时使用该token。
首先,我们将token存储在本地存储中。在这个例子中,我们使用localStorage.setItem()方法将token存储在名为"token"的键中。
localStorage.setItem("token", response.data.token);
然后,在发送axios调用API时,我们从本地存储中获取token,并将其作为授权标头的一部分传递给API。我们可以使用localStorage.getItem()方法来获取token,并将其放入axios请求的headers中。
const token = localStorage.getItem("token"); axios .get("/api/endpoint/", { headers: { "Content-Type": "application/json", Authorization: "Bearer " + token } }) .then(response => (this.expenses = response.data));
通过这样的处理,我们可以确保在每次发送axios请求时,都会在授权标头中传递正确的token,使API能够正确验证请求的合法性。
问题的出现原因是,在Login.vue文件中,通过axios.post方法发送登录请求,并将返回的token存储在localStorage中。然后,在Dashboard.vue文件中,通过axios.get方法发送获取用户信息的请求,并在请求头中附带上存储在localStorage中的token。但是,如果获取用户信息的请求返回状态码为401(未授权),则会移除localStorage中的token,并将页面重定向到登录页面。
解决方法是,确保在发送获取用户信息请求之前,将存储在localStorage中的token添加到请求的Authorization头中。具体而言,在Dashboard.vue文件的created函数中,需要添加如下代码:
axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`;
这样就可以在发送获取用户信息请求时,附带上正确的token。同时,在获取用户信息请求中,还需要处理请求返回状态码为401的情况,移除localStorage中的token,并将页面重定向到登录页面。
以上就是关于(Laravel Sanctum + Vue Auth)这个问题的出现原因以及解决方法。