首页 文章

让授权拦截器不拦截对证书 endpoints 的请求

提问于
浏览
1

我有一个拦截器,它将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');
  }
}

我还有一个登录表单,向证书服务器发送请求到凭证 endpoints :

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);
  }

问题是拦截器正在拦截对证书 endpoints 的上述请求 .

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

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

我的设计首先是否有缺陷?

我正在使用棱角分明 6.0.4

1 回答

  • 0

    HttpRequest具有您可以使用的url属性:

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

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

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

相关问题