gpt4 book ai didi

typescript - HttpInterceptor 上的递归过多

转载 作者:行者123 更新时间:2023-12-04 02:58:07 26 4
gpt4 key购买 nike

在我的应用程序中,身份验证基于 JWT token 。为了使它们无效,我在 JWT 中放置了一个随机安全字符串,并将完全相同的字符串存储在数据库中,与拥有 token 的用户相关联。这两个必须匹配 JWT 才有效。当用户注销时,API 会生成另一个随机字符串并替换数据库中的旧字符串,从而使 JWT 对该用户无效,因为 de JWT 中的字符串与数据库中的字符串不匹配。

为此,我需要一个拦截器,它在每次向 API 发出请求之前发出静默请求,以检查随机字符串是否相等。基于this问题是,我的拦截器可以工作但表现怪异,发出无限请求并抛出“太多递归”错误。

我做错了什么?

拦截器

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

错误截图

Error screenshot

最佳答案

您在代码中创建了无限循环:

  1. 您开始于:http://localhost:53448/api/... 请求

  2. 您的 HttpInterceptor 会捕获它。因为url匹配(/api\//)格式,所以调用了this.CheckRevogToken()方法

  3. CheckRevogToken() 中,您创建了一个监听器,并发送到以下 url:"http://localhost:53448/api/check_revog_token"

  4. 您的发布请求又一次被 HttpInterceptor 捕获。因为 url 再次匹配 (/api\//),所以重复第 2 步。

关于typescript - HttpInterceptor 上的递归过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51945562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com