【发布时间】:2018-04-01 03:59:46
【问题描述】:
所以我开始为我的 SPA 使用 Laravel 的 Tymon JWT 包。一切顺利(添加用户、登录、获取 Auth 用户),但是当我发出 API 请求时,它只能工作一个小时。我了解我在登录时存储的令牌已过期,因此当我在 60 分钟后向 API 发出请求时,它不起作用。我的问题是如何刷新令牌并将其恢复到本地存储中?在一个新的请求?每 59 分钟一次?
AuthController.php
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Sorry, we cant find you.']);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
$user = JWTAuth::toUser($token);
//Fire off the login event
event( new LoginSuccessful($user) );
return response()->json( compact('token', 'user') );
}
登录.vue
axios.post('/api/authenticate',{
email: this.email,
password: this.password
})
.then(response => {
if(response.data.error){
//Show the error
this.error = response.data.error
this.loading = false;
} else {
this.loading = false;
//Store the items in storage
localStorage.setItem('jwt_token', response.data.token);
localStorage.setItem('user', JSON.stringify(response.data.user));
//Mutate the state
this.$store.commit('login');
//Now go to the dashboard
this.$router.push('dashboard');
}
})
.catch(error => {
});
在我的头标签中
<script>
window.hopbak = {
'jwt_token': localStorage.getItem('jwt_token'),
'csrfToken': {!! json_encode( csrf_token() ) !!},
};
</script>
在我的 bootstrap.js 中
let token = window.hopbak.jwt_token;
if (token) {
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
} else {
console.log('no token');
}
【问题讨论】:
-
这是高级别的,没有任何代码可以提供帮助,但是当您收到 API 令牌返回时,我会将其与刷新令牌一起存储在本地存储中。然后,当您进行 API 调用时,添加一个 catch 以检查错误是否与 API 令牌已过期有关,如果确实如此,则使用刷新令牌获取新的 API 令牌,然后自动重试原始请求。