node.js - 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 新手,感谢您对我的教育。
解决方案
推荐阅读
- phpunit - 如何在文本输出中获得简单的 phpunit 代码覆盖率摘要?
- python - 有没有一种混合错误处理和上下文管理的pythonic方法?
- numpy - 使用 sklearn 对 MNIST 数据集进行手写数字识别
- reactjs - NextJs - 链接以滚动到同一页面中的某个部分
- apache-spark - 为什么 Spark Standalone 与 dockerized 工作人员一起显示不正确的“正在使用的内存”总数
- php - codegniter 3 莫莉问题
- c# - Blazor 服务器在身份验证后添加声明
- node.js - 对于 gulp 4.0.2 依赖漏洞我该怎么办?
- oracle - 如何确定这些字符存储在 Oracle 数据库中,以便正确配置 Putty 会话?
- go - 在什么时候例程实际上阻塞了?