刷新令牌角度 [英] Refresh token Angular
问题描述
我已经创建了一个服务,用于从我的角度应用程序调用API.在该服务中,我声明了ROOT_URL和TOKEN变量并为其分配了值.
I have created a service for calling API from my angular application. In that service, I have declared ROOT_URL and TOKEN variables and assigned values for these.
在声明之下,使用上述ROOT_URL和TOKEN的API的get方法很少.
Below the declaration, there are few get methods to API using the above ROOT_URL and TOKEN.
我面临的问题是,此令牌值每24小时过期一次,因此我每天必须更改该值.我使用以前的令牌使用邮递员获取刷新令牌.
Issue i am facing is, this TOKEN value is expired every 24 hours so that i have to change the value everyday. I use the previous TOKEN to get a refresh token using postman.
有人可以给我一个解决方案,我该如何实现每次TOKEN过期时自动发生的事情?
Can some one give me a solution how can i implement this will happen automatically every time when TOKEN expires?
推荐答案
通常,来自API的HTTP响应标头中包含一些内容,表明该客户端曾经通过身份验证,但现在具有过期的令牌.通常,响应头具有称为令牌过期或www-authenticate的属性.您必须在开始刷新令牌过程之前进行检查.
Usually, the HTTP response header that comes from the API has something that indicates that this client once was authenticated but now has an expired token. Typically, the response header has a property called token-expired or www-authenticate; you have to check this before starting the refreshes token process.
代码示例:
AuthInterceptor
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
HttpErrorResponse
} from '@angular/common/http';
import { AuthService } from '../services/auth.service';
import { Observable, BehaviorSubject, throwError } from 'rxjs';
import { environment } from 'src/environments/environment';
import { filter, switchMap, take, catchError } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private tryingRefreshing = false;
private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
constructor(public authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.authService.getToken();
request = this.addAuthorization(request, token);
return next.handle(request).pipe(catchError(error => {
if (error instanceof HttpErrorResponse && error.status === 401) {
const tokenExpired = error.headers.get('token-expired');
if (tokenExpired) {
return this.handle401Error(request, next);
}
this.authService.logout();
return throwError(error);
} else {
return throwError(error);
}
}));
}
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if (!this.tryingRefreshing) {
this.tryingRefreshing = true;
this.refreshTokenSubject.next(null);
return this.authService.refreshToken().pipe(
switchMap((token: any) => {
this.tryingRefreshing = false;
this.refreshTokenSubject.next(token);
return next.handle(this.addAuthorization(request, token));
}));
} else {
return this.refreshTokenSubject.pipe(
filter(token => token != null),
take(1),
switchMap(jwt => {
return next.handle(this.addAuthorization(request, jwt));
}));
}
}
addAuthorization(httpRequest: HttpRequest<any>, token: string) {
return httpRequest = httpRequest.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
}
刷新令牌
这只是显示share()方法的示例方法.
refreshToken(): Observable<string> {
return this.http.post<any>(`${this.baseUrl}/auth/token/refresh-token`, {}, { withCredentials: true })
.pipe(
share(),
map((authResponse) => {
this.currentAuthSubject.next(authResponse);
this.addToLocalStorage(authResponse);
return authResponse.token;
}));
}
这篇关于刷新令牌角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!