因此,我开始为我的SPA使用用于Laravel的Tymon JWT包。它的一切都很好(添加用户,登录,获得Auth用户),但是当我提出API请求时,它只能工作一个小时。我知道我在登录时存储的令牌会过期,所以当我在60分钟后向API发出请求时,它不起作用。我的问题是如何刷新令牌并将其恢复到本地存储中?在新的请求?每59分钟?TYmon存储在localstorage中的智威汤逊Laravel Vue刷新令牌
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'));
}
Login.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标记,然后自动重试原始请求。 – James