首页 > 解决方案 > Angular7:拦截器没有被击中的问题,无法弄清楚

问题描述

可能听起来微不足道,但是,我在后端有逻辑来验证用户是否属于白名单用户,基于此我授权用户继续。想法是如果用户不在列表中,则将其移动到 403 页面。这是一个项目要求,不能在这里使用内置的 authguard 等概念。

这是后端代码,它工作正常。当用户未经过身份验证时,它直接发布到索引页面。

import * as express from 'express';

let router = express.Router();
router.use("/", (req, res, next) => {
let userName = userService.getUser(req);
if(req.originalUrl.indexOf('') !== -1 && userService.validateUser(userName) === false){
    console.log('[WARN] Not authorized access by user : '+ userName);
    return res.status(403).send("Authorization failure: Contact the EIS team to get access to this site.");
}}

现在我写了一个应用拦截器服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { HttpInterceptor, HttpRequest, HttpEvent, HttpHandler, HttpResponseBase } from '@angular/common/http';

@Injectable()
export class AppInterceptorService implements HttpInterceptor {
    // constructor(http: HttpClient) {
    //         console.log('construcot AppInterceptorService');
    // }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('********** coming*********');
      return next.handle(req).do(event => {
          console.log('********** coming');
        if (event instanceof HttpResponseBase) {
          const response = event as HttpResponseBase;
          if (response.status === 403) {
            window.location.href = 'https://my-403-page.com';
            return next.handle(req);
          }
        }
      });
    }
  }

我的 app.module.ts 包括拦截器

providers: [
{
  provide: HTTP_INTERCEPTORS,
  useClass: AppInterceptorService,
  multi: true
}
],

还在 app.module.ts 中导入了 HTTPClientModule,

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http' 

可选信息 --> 在 app.component.ts 中:

import { HttpClient } from '@angular/common/http';
export class AppComponent implements OnInit {
title = 'Upgrade Service Admin UI'

public user: User
public serviceVersion: ServiceVersion
private _userSub$: Subscription
private _serviceVersionSub$: Subscription

constructor(private _http: HttpClient, private _cdr: ChangeDetectorRef) {
}

ngOnInit() {
  console.log('appcomponent loading')
  this._serviceVersionSub$ = this._http.get('version')
.subscribe(data => {
  this.serviceVersion = data as ServiceVersion
  this._cdr.markForCheck()
})
this._userSub$ = this._http.get('user')
.subscribe(data => {
  this.user = data as User
  this._cdr.markForCheck()
})

我无法弄清楚是什么导致拦截器未被检测到。Angular 新手,感谢您对我的教育。

标签: node.jsangularangular-ui-router

解决方案


推荐阅读