gpt4 book ai didi

angular - 如何使用 adal-angular5 在 angular 5 中刷新 token

转载 作者:行者123 更新时间:2023-12-01 05:54:10 26 4
gpt4 key购买 nike

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

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

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

最佳答案

请尝试以下方法,看看是否有效,

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

关于angular - 如何使用 adal-angular5 在 angular 5 中刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50894546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com