本文介绍了Adal Angular 4-刷新令牌未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用adal-angular4( https://www.npmjs.com/package/adal-angular4 )用于我的Angular 7应用程序中的Azure AD身份验证.adal-angular提供了一个有效期为1 hr的访问令牌.我需要实现刷新令牌功能,以便使用AdalService的acquireToken()方法获取新令牌.我添加了必需的逻辑,以使用AcquireToken()方法获取刷新令牌.我什至获得了Refreshed Token,但是在Token过期后,我的会话仍然过期.我编写了每5分钟运行一次的逻辑.逻辑检查令牌到期的纪元时间与当前时间之间的差异.如果时间差少于5分钟,则我调用AdalService acquisitionToken()方法,该方法将向我返回新的令牌.但是,令牌仍然在1小时后过期,并且我的会话超时.

I am using adal-angular4 (https://www.npmjs.com/package/adal-angular4) for Azure AD Authentication in my Angular 7 application.adal-angular provides an Access Token whose validity is 1 hr.I need to implement Refresh Token functionality so that I acquire new Token using acquireToken() method of AdalService. I have added required logic to get the Refresh Token using acquireToken() method. I even get the Refreshed Token but still my session gets expired after Token is expired.I have written logic which runs every 5 minutes. The logic checks the difference of Epoch time of Token expiration and current time. If this difference in time is less that 5 minutes then I call AdalService acquireToken() method which returns me new Token. However, still the Token expires after 1 hour and my session Time outs.

以下是我的代码详细信息:-app.component.ts

Below is my code details:-app.component.ts

ngOnInit() {

    // Acquire Refresh Token
    if (this.adalService.userInfo.authenticated) {
      setInterval(() => {
        this.authService.refreshToken(); }, 300000); // 300000 ms = 5 minutes
    }
  }

auth.service.ts

auth.service.ts

refreshToken(): boolean {
        const token = this.adalService.userInfo.token;
        const decodedToken = jwt_decode(token);
        const tokenExpiresIn = decodedToken['exp'];
        const currentEpochTime = Math.floor(new Date().getTime() / 1000.0);
        const epochDiffInMins = Math.floor((tokenExpiresIn - currentEpochTime) / 60); // Epoch time difference in minutes
        if (epochDiffInMins < 5) {
        this.adalService.acquireToken(environment.adalConfig.clientId).toPromise().then((data) => {
            this.processLoginRequest(this.adalService.userInfo);
            return true;
        },
        (error) => {
            return false;
        });
        }
        return false;
    }

processLoginRequest(response: any) {
        if (response) {
            localStorage.setItem(Constants.localStorageKeys.isLoggedIn, 'true');
            localStorage.setItem(Constants.localStorageKeys.apiToken, JSON.stringify(response.token));
            localStorage.setItem(Constants.localStorageKeys.userId, response.userName);
            location.reload();
        }
    }

auth-gaurd.service.ts

auth-gaurd.service.ts

@Injectable()
export class AuthGuardService implements CanActivate {
    constructor(
        private router: Router,
        private logger: LoggerService,
        private authService: AuthService,
        private adalService: AdalService
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        const url: string = state.url;

        if (!this.adalService.userInfo.authenticated) {
            this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
            return false;
        }
        return true;
    }
}

任何快速帮助将不胜感激.预先感谢.

Any Quick help will be appreciated. Thanks in Advance.

推荐答案

您必须为所有http请求(获取/发布/更新/删除)调用 this.adalService.acquireToken 方法.创建一个拦截器/http包装器类并拦截每个http请求,然后调用 this.adalService.acquireToken (始终返回当前有效令牌),并将返回的令牌设置为的Authorization标头每个http请求.您必须将配置设置为"expireOffsetSeconds":1200 (表示新令牌将在到期前20分钟生成,即,每40分钟将生成新令牌).expireOffsetSeconds的默认值为120(2分钟),应将其增加到更高的值,以避免令牌刷新方法返回空值.适用于我的配置是1200.

You have to call this.adalService.acquireToken method for all the http requests (get/post/update/delete). Create an interceptor/http wrapper class and intercept each http request, then call the this.adalService.acquireToken (returns you the current valid token always) and set the returned token to the Authorization header of each http request. You have to set a configuration of "expireOffsetSeconds": 1200 (means the new token will be generated 20 minutes before expiration. ie, every 40th minute a new token will get generated). The default value of expireOffsetSeconds is 120 (2 minutes), which should be increased to some higher value to avoid token refresh method returning null value. The configuration worked for me is 1200.

请参考以下链接,以了解如何创建http Wrapper类以拦截每个请求并遵循这些步骤, https://www.npmjs.com/package/adal-angular5

Refer the below link to see how to create an http Wrapper class to intercept every request and follow the steps too,https://www.npmjs.com/package/adal-angular5

这篇关于Adal Angular 4-刷新令牌未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:46