I work on a JHipster generated application with Angular4/Spring.
When I log on the app, I can call the API for 1800 seconds. However when I run a request, the expiration date of my token should be reset and I should not be disconnected after this time.
In my table oauth_client_details
, I have the fields access_token_validity
and refresh_token_validity
on 1800 each.
Is there something else to set up so that the token is properly updated?
Here's a trick to refresh session duration with the refresh token.
In auth-oauth2.service.ts, replace authSuccess() function and add a refresh() one.
authSuccess(resp) {
const response = resp.json();
const expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
response.expires_at = expiredAt.getTime();
this.$localStorage.store('authenticationToken', response);
if (this.refreshSubcription !== null) {
// cancel previous refresh
this.refreshSubcription.unsubscribe();
}
// refresh token 5 seconds before expiration
this.refreshSubcription = Observable
.timer((response.expires_in - 5) * 1000 )
.take(1)
.subscribe(() => this.refresh());
return response;
}
refresh() {
const data = 'refresh_token=' + this.getToken().refresh_token + '&grant_type=refresh_token&scope=read%20write&' +
'client_secret=<SECRET-TOKEN>&client_id=<CLIENT-ID>';
const headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Bearer ' + this.getToken().access_token
});
this.http
.post('oauth/token', data, {headers})
.map(this.authSuccess.bind(this))
.subscribe();
}
Remember to modify the logout() and login() methods accordingly.
login(credentials): Observable<any> {
const data = 'username=' + encodeURIComponent(credentials.username) + '&password=' +
encodeURIComponent(credentials.password) + '&grant_type=password&scope=read%20write&' +
'<SECRET-TOKEN>&client_id=<CLIENT-ID>';
const headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Basic ' + this.base64.encode('<CLIENT-ID>' + ':' + '<SECRET-TOKEN>')
});
return this.http
.post('oauth/token', data, {headers})
.map(this.authSuccess.bind(this));
}
logout(): Observable<any> {
if (this.refreshSubcription !== null) {
// cancel previous refresh
this.refreshSubcription.unsubscribe();
}
return new Observable((observer) => {
this.http.post('api/logout', {});
this.$localStorage.clear('authenticationToken');
observer.complete();
});
}