【问题标题】:Have the authorization interceptor not intercept requests to the credentials endpoint让授权拦截器不拦截对凭据端点的请求
【发布时间】:2018-08-23 09:30:17
【问题描述】:

我有一个拦截器,可以将 JWT 访问令牌添加到针对资源服务器的请求:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private keycloakClientService: KeycloakClientService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    return this.addAuthHeader(request, next);
  }

  private addAuthHeader(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('=======>> Intercepting the http request to add the jwt token in the header');
  }
}

我还有一个登录表单,向授权服务器发送对凭据端点的请求:

  login(): void {
    this.userRestService.login(this.username, this.password).subscribe(
      data => {
        this.authService.setJwtTokenToLocalStorage(data.token);
        this.router.navigate(['user']);
      }
    );
  }

  public login(ussername: string, password: string): Observable<any> {
    console.log('Sending the login credentials to obtain a token');
    const credentials = { username: ussername, password: password };
    const url: string = environment.USER_REST_URL + '/login';
    return this.httpClient.post(url, credentials);
  }

问题是拦截器正在拦截上述对凭据端点的请求。

我希望拦截器只拦截发送到资源服务器所有端点的包含 JWT 访问令牌的请求,但不拦截发送到授权服务器凭据端点的请求。

我应该使用一些 URI 模式匹配吗?

我的设计一开始就有缺陷吗?

我正在使用角度 6.0.4

【问题讨论】:

    标签: angular


    【解决方案1】:

    HttpRequest 有一个可以使用的url 属性:

    if (/^\/login$/.test(request.url)) {
        return next.handle(request);
    }
    

    如果您需要参数来做出决定,还有一个urlWithParams

    请注意,立即调用 next.handle() 会使您的拦截器成为 noop,而其他拦截器将被执行,就像您的拦截器不存在一样。

    【讨论】:

    • 感谢这个代码块。我知道它应该位于拦截器内。有什么办法根本不触发拦截器?
    • 我不认为这是可能的:HttpClient 使用一串拦截器,第一个被执行,它需要将控制器传递给下一个,然后链开始。因此,每个拦截器最终都会按顺序执行。即使你的拦截器没有任何事情要做,之前的拦截器也不知道,所以它仍然会将控制权交给你的拦截器。现在,如果你的拦截器不应该做任何事情,只需调用next.handle,它将控制权传递给下一个拦截器(我更新了我的答案,注意到我之前错过了调用 next.handle)。
    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2010-11-21
    • 1970-01-01
    相关资源
    最近更新 更多