So I started using Tymon JWT package for Laravel for my SPA. Its all going good ( adding user, signing in, getting Auth user) but when I make an API request it only works for an hour. I understand that the token I stored on login expires so when I make a request to the API after 60 minutes it doesn't work. My question is how do I refresh the token and restore it in my local storage? On a new request? Every 59 minutes? I am just confused on the process. Right now my app just checks if there is a token in local storage to bypass login as well, should this check against the refresh token as well??? I have yet to find a clear example of how to do this with Laravel and Vue (seems like with this being a laravel package there would be somewhere)
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 => {
});
So I started using Tymon JWT package for Laravel for my SPA. Its all going good ( adding user, signing in, getting Auth user) but when I make an API request it only works for an hour. I understand that the token I stored on login expires so when I make a request to the API after 60 minutes it doesn't work. My question is how do I refresh the token and restore it in my local storage? On a new request? Every 59 minutes? I am just confused on the process. Right now my app just checks if there is a token in local storage to bypass login as well, should this check against the refresh token as well??? I have yet to find a clear example of how to do this with Laravel and Vue (seems like with this being a laravel package there would be somewhere)
AuthController.php
Login.vue
in my head tag
in my bootstrap.js
in my store.js