如何在角度4中添加自定义拦截器

时间:2018-06-20 19:19:13

标签: angular typescript angular-ui-router angular-http-interceptors

我已经在angular 4上编写了一个自定义拦截器。我遇到的问题是使用URL中的动态路径变量检查URL。后端应用程序具有Oauth2,并且已部署在单独的服务器(授权和资源)中。角钢的拦截器等级低于

export class TokenInterceptor implements HttpInterceptor {
    private whiteList = [
        'http://localhost:8081/Test1app/oauth-server/oauth/token',
        'http://localhost:8080/ResourceApp/oauth-resource/ibex/api/signup',
        'http://localhost:8080/ResourceApp/oauth-resource/ibex/api/registeration/confirm/**',
        'http://localhost:8080/ResourceApp/oauth-resource/ibex/api/user/profile/upload',
        'http://localhost:8080/ResourceApp/oauth-resource/ibex/api/profile/edit/password/**'
    ]
    constructor(public auth : AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log(request.url);
        // If request is not in whitlist add header
        if (!this.whiteList.includes(request.url)) {
            console.log("I was not here");
            console.log(request.url);
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${this.auth.getToken()}`
                }
            });
        }

        return next.handle(request);
    }

}

我现在面临的问题是每当我尝试访问http://localhost:8080/ResourceApp/oauth-resource/ibex/api/profile/edit/password/12345-2333-4444时 它处于if条件下(请求在白名单中)

1 个答案:

答案 0 :(得分:1)

尝试一下:

export class TokenInterceptor implements HttpInterceptor {
  private patterns = [
    new RegExp('http://localhost:8081/Test1app/oauth-server/oauth/token'),
    new RegExp('http://localhost:8080/ResourceApp/oauth-resource/ibex/api/signup'),
    new RegExp('http://localhost:8080/ResourceApp/oauth-resource/ibex/api/registeration/confirm/.*'),
    new RegExp('http://localhost:8080/ResourceApp/oauth-resource/ibex/api/user/profile/upload'),
    new RegExp('http://localhost:8080/ResourceApp/oauth-resource/ibex/api/profile/edit/password/.*')
  ];

  constructor(public auth : AuthenticationService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!this.match(request.url)) {
      request = request.clone({ setHeaders: { Authorization: `Bearer ${this.auth.getToken()}` } });
    }

    return next.handle(request);
  }

  match(url: string): boolean {
    for (const pattern of this.patterns) {
      if (Array.isArray(url.match(pattern))) { return true; }
    }

    return false;
  }

}

参考文献:

String.prototype.match()

Regular Expressions