当前位置: 首页 > 知识库问答 >
问题:

Angular 4和OAuth-截获401响应,刷新访问令牌并重试请求

黄昊英
2023-03-14

正如标题所说,我正在使用OAuth身份验证进行Angular 4项目。

每当http请求以状态代码401响应时,我将拦截该请求,续订访问令牌并重试失败的请求。

当我收到401时,请求被正确截获,访问令牌被刷新。失败的请求也会再次执行,但不再将其响应传递给组件。

因此,问题在于,我的组件(应该在请求响应上进行观察)在刷新令牌和重试请求之前,会抱怨视图的日志“接收属性时出错”。

我的拦截器:

import { Injectable, Inject, Injector } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpResponse,
  HttpErrorResponse,
  HttpEvent,
  HttpInterceptor,
  HttpSentEvent,
  HttpHeaderResponse,
  HttpProgressEvent,
  HttpUserEvent
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { TokenManager } from '../../../util/TokenManager';
import { AuthUserResponse } from '../../../models/authUserResponse';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class AuthTokenExpiredInterceptor implements HttpInterceptor {

  isRefreshingToken: boolean = false;
  tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);

  constructor( private injector: Injector, private tokenManager: TokenManager ) {}


  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
    return next.handle(this.addNewAccessTokenToHeaders(request, this.tokenManager.retrieveAccessToken()))
    .do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
          console.log('processing response', event);
      }
      return event;
    },(err) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          console.log('Access_token possibly expired, trying to retrieve a new one!')

          return this.handle401Error(request, next);
        } else if (err.status === 400) {
          console.log('Refresh_token possibly expired, redirecting to login');

          return this.handle400Error(err);
        }
      } else {
        return Observable.throw(err);
      }
    });
  }

  handle401Error(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.isRefreshingToken) {
      console.log('in if');
      this.isRefreshingToken = true;

      // Reset here so that the following requests wait until the token comes back from the refreshToken call.
      this.tokenSubject.next(null);

      console.log('About to call renewAccessToken');
      return this.injector.get(AuthService).renewAccessToken().subscribe((response) => {
        let newToken = response.access_token;

        if (newToken) {
          console.log('Got the new access_token!');
          this.tokenSubject.next(newToken);
          let requestToRetry = this.addNewAccessTokenToHeaders(request, newToken);
          console.log('The retried request header: ' + requestToRetry.headers.get("Authorization"));
          return next.handle(requestToRetry);
        } else {  // No token in response
          this.injector.get(AuthService).logout();
        }
      },
      (err) => {
        this.injector.get(AuthService).logout();
        return Observable.throw(err)
      },
      () => {
        console.log('handle401Error done');
        this.isRefreshingToken = false;
      })        
    } else {
      console.log('In else');
      return this.tokenSubject
      .filter(token => token != null)
      .take(1)
      .switchMap(token => {
        return next.handle(this.addNewAccessTokenToHeaders(request, token));
      });
    }
  }


    handle400Error(error: HttpErrorResponse) {
      if (error && error.status === 400 && error.error && error.error.error === 'invalid_grant') {
        this.injector.get(AuthService).logout();
      }

        return Observable.throw(error);
      }

    addNewAccessTokenToHeaders(req: HttpRequest<any>, token: string): HttpRequest<any> {
      console.log('Adding the access_token to the Authorization header');
      return req.clone({ setHeaders: {
        Authorization: 'Bearer ' + token
      }})
    }
  }

我的服务返回一个可观察的

和我的组件:

ngOnInit(){
    this.getProperties();
  }

  getProperties() {
    this.propertyService.getProperties().subscribe(
      result => {
      this.properties = result;
      console.log('Received response in Properties component: ' + JSON.stringify(result));
    }, error => {
      console.log('Error receiving the properties for the view')
    },
    () => { console.log('Received the properties, now they can be displayed in the view') })
  }

共有1个答案

高承望
2023-03-14

函数拦截必须始终返回可观察的

我有一个这样的截取(我希望代码可以帮助你)

constructor(private inj: Injector) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //if the request has "Authorization" we return the request
    if (req.headers.has('Authorization'))
      return next.handle(req);

    //I get here the AuthService
    const auth = this.inj.get(AuthService);

    //create the httpHeaders
    const httpHeaders = new HttpHeaders()
      .set('Content-Type', 'application/json; charset=utf-8')
      .set('Authorization', '' + auth.SID) //<-- I use auth.SID

    const authReq = req.clone({ headers: httpHeaders });

    return next.handle(authReq).catch((err: any) => { //<--if error use a catch
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          //auth.recoverSID return a Observable<{value:new SID}>
          //use switchMap to really return next.handle(authReq)
          return auth.recoverSID().switchMap((value: IResponse) => {
            let httpHeaders = new HttpHeaders()
              .set('Content-Type', 'application/json; charset=utf-8')
              .set('Authorization', '' + value.SID)

            const authReq = req.clone({ headers: httpHeaders });
            return next.handle(authReq);
          })
        };
      }
      //Other case throw an error
      return Observable.throw(err);
    });
  }
 类似资料:
  • null 很抱歉太啰嗦了。 提前谢了。

  • 本文向大家介绍oauth 刷新访问令牌,包括了oauth 刷新访问令牌的使用技巧和注意事项,需要的朋友参考一下 示例 资源

  • 我如何从第一次授权代码中获得刷新令牌和访问令牌?并且,我如何重用这个刷新令牌来获得一个新的访问令牌,以便使用Java API上传到Google Drive?这不是一个web应用程序。它在Java Swing代码中。

  • 我已经阅读了JWT和访问令牌和刷新令牌。我知道您必须在很短的时间(分钟)内设置访问令牌过期,并在过期时使用刷新令牌获取新的访问令牌。 我不清楚三件事: 谁检查访问令牌是否过期?客户端是否通过发送过期的访问令牌和刷新来检查并请求新的访问代码? 谁检查刷新令牌是否过期?(显然刷新令牌也需要过期,尽管需要更长的时间才能过期)。 在我看来,如果刷新令牌过期,则必须提示用户重新登录。在某些情况下(移动应用)

  • 引用的员额: 为什么OAuth v2既有访问令牌又有刷新令牌? 刷新令牌有什么意义?

  • 我在刷新访问令牌时得到这个错误:访问令牌无法刷新。请重新验证 这一错误此前曾在2017年4月报告过。OneLogin文档声明刷新令牌可以使用45天左右。我的刷新令牌已经有20个小时了。是文档正确还是刷新令牌的寿命更短?我可以做获取访问令牌和撤销令牌罚款。 public RootObject RefreshToken(HttpRequesterDM rDM){restsharp.deserializ