typescript 刷新令牌keycloak js

pftdvrlh  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(216)

我使用keycloak-js版本8.0.1,我有一个函数getToken,它测试令牌是否过期,如果过期,它会刷新它,或者令牌没有过期,它会返回它。

令牌服务

@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);
        }
    });
 }
}
dtcbnfnu

dtcbnfnu1#

我认为问题可能是函数TokenService.auth.authz.updateToken(1800),这意味着(如果我理解正确的话),如果令牌将在1800秒内过期,则刷新令牌。
在您的例子中,令牌已经过期,因此函数不做任何事情。

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);
    });
 }

相关问题