3

我有一个身份验证拦截器,但是,我希望这个拦截器过滤请求,而不是在用户访问不需要用户身份验证的确认帐户密码等组件时应用。关于如何去做的任何例子?这是身份验证拦截器的逻辑:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth token from the service.
    let authToken = this.authService.getToken();
    let authHeader = 'Bearer ' + authToken;

    //For requests that are retried, we always want a fresh copy, else the request will have headers added multiple times.
    //So Clone the request before adding the new header. 
    //NOTE: the cache and pragma are required for IE that will otherwise cache all get 200 requests.
    const authReq = request.clone({
      setHeaders: {
        Authorization: authHeader,
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      }
    });
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
}
4

1 回答 1

1

对于这种情况,您的请求 URL 很有帮助。

假设您的身份验证 url 是这样的auth/login or auth/refreshToken,并且您的资源 api url 是这样的api/users, api/users/123, api/addUser,那么您可以设置一个if条件来检查请求的目的。

url匹配示例:-

 if (request.url.match(/api\//)) { // api call
    console.log('api call detected.');
    let authToken = this.authService.getToken();
    let authHeader = 'Bearer ' + authToken;
    const authReq = request.clone({
    setHeaders: {
       Authorization: authHeader,
       'Cache-Control': 'no-cache',
       'Pragma': 'no-cache'
     }
    });
    return next.handle(authReq);
 }
 else{ // auth call - you can put esle if conditions if you have more such pattern
 console.log('auth call detected.');
    return next.handle(request);
 }     

现在authentication headers只会添加到您的 api-call(我的意思是资源 api-call)中,其他调用不会被修改。

注意:我从事 Java、DB 等后端技术的时间较长,现在是第一次学习 Angular,所以回答得像一个 mod :P,但这个想法来自我上一个 Java 项目。希望能帮助到你..!!:)

于 2017-12-14T15:54:42.790 回答