Reputation: 2013
I work with keycloak-js version 8.0.1, i have a function getToken that tests either the token is expired in that case it refreshes it, or the token is not expired so it returns it. The problem is that when the token is expired it displays the warning msg but it does't change it
TokenService
@Injectable()
export class TokenService {
static auth: any = {};
constructor() { }
static init(): Promise<any> {
const keycloakAuth: Keycloak.KeycloakInstance = Keycloak({
url: config.keycloak.url,
realm: config.keycloak.realm,
clientId: config.keycloak.clientId
});
return new Promise((resolve, reject) => {
keycloakAuth.init({ onLoad: 'check-sso', flow: 'implicit', checkLoginIframe: false }).success(() => {
TokenService.auth.authz = keycloakAuth;
resolve();
}).error(() => {
reject();
});
});
}
getToken(): Promise<string> {
return new Promise<string>((resolve, reject) => {
if (TokenService.auth.authz.isTokenExpired()) {
console.warn("Token expired !");
TokenService.auth.authz.updateToken(1800).success(() => {
console.log("Token updated");
resolve(<string>TokenService.auth.authz.token);
}).error(() => {
reject('Failed to refresh token');
});
} else {
resolve(<string>TokenService.auth.authz.token);
}
});
}
}
Upvotes: 0
Views: 3688
Reputation: 300
I think the problem can be the function TokenService.auth.authz.updateToken(1800)
, this means (if i understand correctly), if the token is going to be expired within 1800 secs then do refresh token.
In your case, the token is already expired, therefore the function does not do anything. I suggest not to check isExpired(), but do directly something like this
getToken(): Promise<string> {
return new Promise<string>((resolve, reject) => {
TokenService.auth.authz.updateToken(100).success(() => {
console.log("Token updated");
resolve(<string>TokenService.auth.authz.token);
}).error(() => {
reject('Failed to refresh token');
});
resolve(<string>TokenService.auth.authz.token);
});
}
Upvotes: 1