在我的应用程序中,身份验证基于JWT令牌。为了使它们失效,我在JWT中放置了一个随机的安全字符串,并将完全相同的字符串存储在数据库中,与拥有令牌的用户相关联。这两个必须匹配JWT才能有效。当用户注销时,API会生成另一个随机字符串并替换数据库中的旧字符串,使JWT对该用户无效,因为de中的字符串与数据库的字符串不匹配。
要做到这一点,我需要一个拦截器,它在每次请求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);
}
)};
} 错误截图

发布于 2018-08-21 09:34:11
您已经在代码中创建了无限循环:
http://localhost:53448/api/...请求HttpInterceptor抓到它了。因为url与(/api\//)格式匹配,所以调用this.CheckRevogToken()方法CheckRevogToken()中,您将创建一个听者,并将文章发送到以下url:"http://localhost:53448/api/check_revog_token"HttpInterceptor再捕获一次。因为url再次与(/api\//)匹配,所以重复步骤2。https://stackoverflow.com/questions/51945562
复制相似问题