角度9拦截XHR请求添加Bearer令牌

时间:2020-04-06 10:21:11

标签: angular token angular-http-interceptors

我想拦截所有xhr请求以在我的Angular应用中添加身份验证,为此,我添加了一个HttpInterceptor,但并未为XHR请求触发,我不知道如何拦截这些请求??

谢谢。

auth.interceptor.ts

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private oktaAuth: OktaAuthService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.handleAccess(request, next));
  }

  private async handleAccess(request: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> {
    // Only add an access token to whitelisted origins
    const allowedOrigins = ['http://localhost'];
    console.log('Intercept HTTP request to adding Bearer token');
    if (allowedOrigins.some(url => request.urlWithParams.includes(url))) {
      const accessToken = await this.oktaAuth.getAccessToken();
      if (accessToken) {
        request = request.clone({
          setHeaders: {
            Authorization: 'Bearer ' + accessToken
          }
        });
      } else {
        //No token; proceed request without bearer token
        console.log('No token added to HTTP request');
        return next.handle(request).toPromise();
      }
    }
    return next.handle(request).toPromise();
  }
}

0 个答案:

没有答案