Refresh token after restart app
Hi, i can`t understand how refresh token after app restart.
In this part says: "...assign the client's tokenResult property to your token" but how?
For example I can save old tokenResul with AppllicationSettings.
@nikozgurskiy always save the refreshtoken from latest token result to applicationsettings. When app boots check for present refreshtoken and use it for renewal
Application init - Check for refresh token or call login
import { ApplicationSettings } from '@nativescript/core';
ApplicationSettings.setString('x-refresh-token', tokenResult.refreshToken);
ngOnInit() {
// Check if refresh token is stored, otherwise return null
const refreshToken = ApplicationSettings.getString('x-refresh-token', null);
// Refresh token missing? attempt a login
if (refreshToken === null) {
this.authService.tnsOauthLogin('keycloakProvider')
.then((result: ITnsOAuthTokenResult) => {
this.loginSuccessfulAction();
})
.catch((e: string) => console.log('Login failed - error: ', e));
}
// else use the refresh token
else {
this.authService.tnsOAuthTokenRefresh('keycloakProvider')
.then((result: ITnsOAuthTokenResult) => {
this.loginSuccessfulAction();
})
.catch((e: string) => console.log('Token refresh failed - error: ', e));
}
}
Login with refresh token function
import { ApplicationSettings } from '@nativescript/core';
import { TnsOAuthClient, ITnsOAuthTokenResult } from 'nativescript-oauth2';
tnsOAuthTokenRefresh(providerType): Promise<ITnsOAuthTokenResult> {
let client = new TnsOAuthClient(providerType);
const token = {
accessToken: null,
refreshToken: ApplicationSettings.getString('x-refresh-token'),
idToken: null,
accessTokenExpiration: null,
refreshTokenExpiration: null,
idTokenExpiration: null,
};
client.tokenResult = token;
return new Promise<ITnsOAuthTokenResult>((resolve, reject) => {
this.client.refreshTokenWithCompletion(
(tokenResult: ITnsOAuthTokenResult, error) => {
if (error) {
console.log(`☠️️ failed to refresh existing token`);
reject(error);
}
else {
console.log(`✔ token refresh ok, redirecting to success link`);
// Store the new token in Application settings (it will be there on next app reload)
ApplicationSettings.setString('x-refresh-token', tokenResult.refreshToken);
resolve(tokenResult);
}
}
);
});
}
All these informations are from the readme file, in fact setting the client's tokenResult with the new object can be a bit misleading.. Anyway, this should work. Consider that the code above is implemented inside an application that in any case, when the token is not valid, login fails, etc.. it will go back to '/login' route by default, the user then will see the login form from the OAuth provider, and attempt another login.