AngularOAuth2OidcBearerTokenisinoneoutoftwoserviceinstancesrequests?
创始人
2024-10-28 19:00:43
0
  1. 在app.module.ts文件中导入OAuthModule和HttpClientModule。

import { HttpClientModule } from '@angular/common/http'; import { OAuthModule } from 'angular-oauth2-oidc'; ...

@NgModule({ imports: [ HttpClientModule, ... OAuthModule.forRoot() ], ... })

  1. 在Service中使用OAuthService手动设置accessToken,并在请求的headers中添加Authorization。

import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { OAuthService } from 'angular-oauth2-oidc';

@Injectable({ providedIn: 'root' }) export class MyService { constructor(private http: HttpClient, private oauthService: OAuthService) {}

getData() { const token = this.oauthService.getAccessToken();

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    Authorization: 'Bearer ' + token
  })
};

return this.http.get('/api/data', httpOptions);

} }

  1. 在拦截器中使用OAuthService自动添加accessToken到请求headers中。

import { Injectable } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { OAuthService } from 'angular-oauth2-oidc';

@Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(private oauthService: OAuthService) {}

intercept(request: HttpRequest, next: HttpHandler): Observable> { const token = this.oauthService.getAccessToken();

if (token) {
  request = request.clone({
    setHeaders: {
      Authorization: `Bearer ${token}`
    }
  });
}

return next.handle(request);

} }

  1. 在app.module.ts中注册拦截器。

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { OAuthModule } from 'angular-oauth2-oidc'; import { TokenInterceptor } from './token-interceptor';

...

@NgModule({ imports: [ HttpClientModule, ... OAuthModule.forRoot() ], ... providers: [ { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true } ] })

这些解决方案将确保OAuth2 OIDC Bearer Token可以在服务请求中正确使用。

相关内容

热门资讯

免费测试版!aapoker透视... 此外,数据分析德州(约局吧德州真的有透视挂吗)辅助神器app还具备辅助透视行为开挂功能,通过对客户约...
必知教程!wepoker破解器... 1、必知教程!wepoker破解器,hhpoker必备开挂,玩家教程(有挂透明)(UU poker、...
玩家必知教程!wepoker透... 玩家必知教程!wepoker透视版下载,hardrock作弊,介绍教程(有挂技巧);致您一封信;亲爱...
攻略讲解!红龙poker辅助工... 攻略讲解!红龙poker辅助工具,pokernow辅助工具,黑科技教程(有挂技巧);玩家必备必赢加哟...
推荐几款新版!aa poker... 推荐几款新版!aa poker辅助,wepoker私人定制透视,解密教程(有挂技巧)关于wepoke...
一分钟秒懂!wepoker辅助... 一分钟秒懂!wepoker辅助是真的假的,wepoker透视脚本免费下载,力荐教程(有挂神器)关于w...
必看攻略!wepoker有透视... 必看攻略!wepoker有透视吗,竞技联盟透视,爆料教程(有挂教程)1、不需要AI权限,帮助你快速的...
盘点一款!wepoker私人局... 1、盘点一款!wepoker私人局辅助挂,agpoker辅助,解密教程(有挂教程);详细教程。2、w...
实测揭晓!线上德州的辅助器是什... 实测揭晓!线上德州的辅助器是什么,wepoker辅助器软件下载,高科技教程(有挂神器)1、不需要AI...
教学盘点!hhpoker有没有... 教学盘点!hhpoker有没有作弊挂,agpoker辅助,规律教程(有挂软件)关于hhpoker有没...