javascript - 设置 laravel 护照的到期时间
问题描述
所以我使用 laravel 护照使用密码授予访问来使我的后端 (laravel) 与 vue.js 一起工作,感谢这个很棒的教程,我终于可以进行身份验证了,但我只是不喜欢他处理令牌的方式,他将令牌保存到浏览器本地存储中,即使我关闭浏览器,也不提供使令牌过期(要求登录)的方法。
我想要的是一种方法让应用程序在空闲几分钟后再次请求登录(没有获取或发布到后端)并且当用户关闭浏览器(而不是选项卡)然后当用户再次打开浏览器然后需要重新输入登录数据(用户名和密码)
所以这就是我如何根据教程处理它的工作方式
首先这是我在 AuthController 上的登录功能
public function login()
{
// check username
$user = User::where('username',request('username'))->first();
if (!$user) {
return response()->json([
'message' => 'Maaf username salah.',
'status' => 422
], 422);
}
// check password
if (!Hash::check(request('password'), $user->password)) {
return response()->json([
'message' => 'Maaf password salah.',
'status' => 422
], 422);
}
Auth::attempt(array('username' => request('username'), 'password' => request('password')));
$client = DB::table('oauth_clients')
->where('password_client', true)
->first();
if (!$client) {
return response()->json([
'message' => 'Maaf terjadi kesalahan konfigurasi.',
'status' => 500
], 500);
}
// Send an internal API request to get an access token
$data = [
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => request('username'),
'password' => request('password'),
];
$request = Request::create('/oauth/token', 'POST', $data);
$response = app()->handle($request);
// Check if the request was successful
if ($response->getStatusCode() != 200) {
return response()->json([
'message' => 'Maaf terjadi kesalahan login, mohon ulangi lagi.',
'status' => 422
], 422);
}
// Get the data from the response
$data = json_decode($response->getContent());
// Format the final response in a desirable format
return response()->json([
'token' => $data->access_token,
'user' => $user,
'status' => 200
], 200);
}
然后在前端(vuejs)上,我在 auth.js 文件上创建此函数以获取返回access_token
并将其存储到本地存储中
login (token, user) {
window.localStorage.setItem('token', token);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
this.token = token;
Event.$emit('userLoggedIn');
}
接下来用于验证用户的每个请求,然后在 auth.js 文件上有检查功能
check () {
return !! this.token;
}
在 app.js 上,我check()
在里面调用这个函数router.beforeEach
router.beforeEach((to, from, next) => {
window.scrollTo(0, 0);
if (to.matched.some(record => record.meta.loggedIn)) {
if (!auth.check()) {
next({
path: '/login',
query: { redirect: to.fullPath }
});
return;
}
}
if (to.matched.some(record => record.meta.notLoggedIn)) {
if (auth.check()) {
next({
path: '/'
});
return;
}
}
next();
});
解决方案
推荐阅读
- flutter - 在 Flutter 中按 Hot restart 时我的屏幕没有更新,我必须再次按 Hot reload
- c# - 如何获得资源的价值?(超过 1 种语言)
- vcf-variant-call-format - 如何在给定染色体编号和位置的情况下检索 SNP 的 rsID
- react-native - 来自包“@react-native-community/async-storage”的异步存储无法在 react-native 中正确检索日期
- spring - NPE SpringLookupInitializer createLookup Spring-Vaadin 19+
- arrays - 如何从SAS中的数组子集中获取大于零的值的计数
- android - 与 Delphi 10.4.2 一起使用的 Android 模拟器
- php - 如何从 txt 文件中读取数组的内容
- reactjs - 我无法使用 npm start 运行反应应用程序如何解决此错误?
- javascript - 向使用 HTML 画布绘制的元素添加文本