Lui*_*ais 3 interceptor typescript angular5
在我的应用程序中,身份验证基于 JWT 令牌。为了使它们无效,我在 JWT 中放置了一个随机安全字符串,并在数据库中放置了与拥有令牌的用户相关联的完全相同的字符串。这两个必须匹配才能使 JWT 有效。当用户注销时,API 会生成另一个随机字符串并替换数据库中的旧字符串,从而使 JWT 对该用户无效,因为 de JWT 中的字符串与数据库的字符串不匹配。
为此,我需要一个拦截器,在对 API 的每个请求之前发出一个静默请求,以检查随机字符串是否相等。基于这个问题,我的拦截器工作但行为怪异,发出无限请求并抛出“递归过多”错误。
我究竟做错了什么?
拦截器
import { TokenService } from './token.service';
import { Router } from '@angular/router';
import { HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
HttpClient,
HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { SharedService } from "./shared-service.service";
import { CookieService } from 'ngx-cookie-service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private sharedService : SharedService,
private httpClient : HttpClient,
private router : Router,
private cookieService : CookieService,
private tokenService : TokenService) {}
token: string;
cd: number;
isExpired: boolean = false;
revog_token: string;
intercept(req: HttpRequest<any>,
next: HttpHandler): Observable<HttpEvent<any>> {
// Check if token exists on cookies
if(this.tokenService.CheckToken()){
if (req.url.match(/api\//)) { // Request to API
console.log("API Request");
this.CheckRevogToken(); // <-- THIS METHOD TRIGGERS THE "TOO MUCH RECURSION" ERROR
}
const cloned = req.clone({ headers: req.headers.set("Authorization","Bearer "+ this.tokenService.GetToken()) });
return next.handle(cloned);
}
else{
return next.handle(req).catch((error, caught) => {
// If status code is 401 ==> Not authorized
if(error.status == 401){
alert("A sua sessão expirou! Será redirecionado para a página de autenticação");
}else{
console.log("Ocorreu um erro");
return Observable.throw(error);
}}) as any;
}
}
CheckRevogToken(){
this.revog_token = this.tokenService.GetRevogFromDecodedToken();
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.httpClient.post("http://localhost:53448/api/check_revog_token", {cd: this.cd, revog_token: this.revog_token}, {headers:headers})
.subscribe(
res => {
console.log(res);
},
err => {
console.log("err: " +err);
}
)};
}
Run Code Online (Sandbox Code Playgroud)
错误截图
您在代码中创建了无限循环:
你开始:http://localhost:53448/api/...请求
你HttpInterceptor抓住了它。因为url匹配(/api\//)格式,然后this.CheckRevogToken()方法被调用
在CheckRevogToken()您创建一个听者,然后发布到以下网址:"http://localhost:53448/api/check_revog_token"
您的帖子请求又一次被 捕获HttpInterceptor。因为 url 再次匹配(/api\//),则重复步骤 2。
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |