所以我正在使用使用laravel护照的密码授予访问权限来使我的后端(laravel)与vue.js一起使用,由于这个awesome tutorial,我终于可以使身份验证工作了,但是我只是不喜欢这种方式他处理令牌,将令牌保存到浏览器本地存储中,即使我关闭浏览器,也无法提供使令牌过期(要求登录)的方法。
我想要的是一种使应用程序在闲置几分钟后(无获取或张贴到后端),以及当用户关闭浏览器(而不是选项卡)然后在用户打开时再次要求登录的方法浏览器再次需要重新输入登录数据(用户名和密码)
所以这是我按照教程处理它的工作方式
首先这是我在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();
});