【问题标题】:Angular 9 http Interceptor get Aws accesstokenAngular 9 http拦截器获取Aws accesstoken
【发布时间】:2021-08-15 12:51:19
【问题描述】:

我正在关注此this 以在 Angular HTTP 拦截器中添加 AWS 访问令牌,但代码进入无限循环,我收到 net::ERR_INSUFFICIENT_RESOURCES 错误。

显示单个字符的token值的console.log。

提前谢谢你

这里是代码

service.ts

 getAccessToken(): Observable<string> {
    return from(Auth.currentSession()).pipe(
      switchMap(session => from(session.getAccessToken().getJwtToken()))
    );
  }

interceptor.ts

/* eslint-disable no-param-reassign */
import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from 'app/user.service';

import { switchMap } from 'rxjs/operators';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public userService: UserService) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return this.userService.getAccessToken().pipe(
      switchMap(jwtToken => {
        console.log(jwtToken);
        // clone the request to add the new header.
        req = req.clone({
          headers: req.headers.set('Authorization', `Bearer ${jwtToken}`),
        });
        if (!req.headers.has('Content-Type')) {
          req = req.clone({
            headers: req.headers.set('Content-Type', 'application/json'),
          });
        }
        return next.handle(req);
      })
    );
  }
}

【问题讨论】:

    标签: angular rxjs angular8 aws-amplify rxjs6


    【解决方案1】:

    在拦截器中使用 http 请求不是一个好习惯。相反,您可以在应用程序打开时拉一次“jwtToken”并将其导入 localStarege。

    在 app.module.ts 中

    import {UserService} from './UserService';
    
    export function appInitializerFn(userService: UserService) {
      return (): Promise<boolean> => userService.getJwtToken()
    }
    
    ...
    
    @NgModule({
     providers : [UserService, {
          provide: APP_INITIALIZER,
          useFactory: appInitializerFn,
          multi: true,
          deps: [UserService]
        },] )
    
    

    在 UserService.ts 中

    @Injectable()
    export class UserService {
       
    
      constructor(private http: HttpClient) {
      }
    
      getJwtToken(): Promise<any> { 
        return this.http
          .get('get/toke/url'))
          .toPromise()
          .then((data: any) => {
            localStorage.setItem("jwtToken", data); 
          }).catch((err: Error) => {  
          }).finally(() => {
            console.info(' token init ');
            return Promise.resolve(true)
          })
      } 
    }
    
    intercept(
       req: HttpRequest<any>,
       next: HttpHandler
     ): Observable<HttpEvent<any>> {
       const jwtToken: string = localStorage.getItem('jwtToken');
    
       req = req.clone({
             headers: req.headers.set('Authorization', `Bearer ${jwtToken}`),
           });
           if (!req.headers.has('Content-Type')) {
             req = req.clone({
               headers: req.headers.set('Content-Type', 'application/json'),
             });
           }
           return next.handle(req);
       );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2017-11-07
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 2020-11-08
      相关资源
      最近更新 更多