如何使用adal-angular5刷新角度5中的标记

时间:2018-06-17 07:21:59

标签: angular angular5 adal angular4-httpclient

我有一个角度项目(版本5.2),并使用ADAL服务(adal-angular5)。在1小时不活动之后,用户从API响应中获得401(未授权)。为避免这种情况,我想在每次调用API之前刷新令牌。我做了一个拦截器。这是我的代码:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Adal5Service } from 'adal-angular5';
import { environment } from '../environments/environment';
import { LoaderService } from './services/loader.service';

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
    constructor(private adalService: Adal5Service, private loaderService: LoaderService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.loaderService.display(true);
        const jwt = this.adalService.userInfo.token;
        const authReq = req.clone({
            url: environment.apiUrl + req.url,
            headers: req.headers
                .set('Content-Type', 'application/json')
                .set('Authorization', 'Bearer ' + jwt)
        });
        return next.handle(authReq).finally(() => this.loaderService.display(false));
    }
} 

请建议我刷新令牌的最佳方法......

2 个答案:

答案 0 :(得分:0)

请尝试以下操作,看看是否有效,

     import { Injectable } from '@angular/core';
     import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } 
     from '@angular/common/http';
     import { Observable } from 'rxjs/Observable';
     import { Adal5Service,Adal5HTTPService } from 'adal-angular5';
     import { environment } from '../environments/environment';
     import { LoaderService } from './services/loader.service';

     @Injectable()
    export class AuthHttpInterceptor implements HttpInterceptor 
    {
        constructor(private adalService: Adal5Service, private loaderService: 
        LoaderService, private adal5HttpService: Adal5HTTPService) { }

       intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> 
       {
          this.loaderService.display(true);
          let headers = new HttpHeaders();
          headers = headers
                   .set('Content-Type', 'application/json')
                   .set('Authorization', 'Bearer ${this.adalService.userInfo.token}');
          let authReq=this.adal5HttpService.get(url, headers )

         return next.handle(authReq).finally(() => this.loaderService.display(false));
    }

答案 1 :(得分:0)

我也遇到了与尖角adal相同的问题,令牌在一小时内过期,我尝试了adal库的RenewToken函数,它正在生成一个新令牌。 调用RenewToken函数后,还需要调用AcquisitionToken方法来更新本地存储中的令牌。