我正在制作一个使用jwt验证数据库调用的角度应用程序。但是问题
就是当令牌在服务器上过期时,由于过期的令牌仍在本地存储中,因此应用程序开始提供空白页而不是数据。经过一些研究,我发现jwt2库可用于跟踪令牌的过期。使用该功能,我必须刷新页面以重定向到登录页面。我仍然能够在组件内移动。我希望令牌过期后立即登录页面或刷新令牌,即使在组件之间移动时,如果令牌过期,则应将用户重定向到登录页面或令牌应该刷新。知道我还需要做什么。请帮助。谢谢。
这是我的身份验证管理员:
Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router,private authService:AuthService ){ }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (!(this.authService.isTokenExpired()) ){
// logged in so return true
console.log("Logged IN");
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return true;
}
}
这是我的身份验证服务:
const helper = new JwtHelperService();
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
/* public login<T>(username: string, password: string): Observable<HttpResponse<T>> {
let headers = new HttpHeaders();
const clientId = 'rosClient';
const secret = 'secret';
headers = headers.append("Authorization", "Basic " + btoa(`${username}:${password}`));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
return this.http.get<T>('/auth/login', {
headers: headers,
observe: 'response'
});
}*/
public login<T>(username: string, password: string): Observable<HttpResponse<T>> {
let headers = new HttpHeaders();
const clientId = 'clientid';
const secret = 'secret';
headers = headers.append('Authorization', 'Basic ' + btoa(`${clientId}:${secret}`));
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
const params = new HttpParams().set('username', username).set('password', password).set('grant_type', 'password').set('scope', 'read');
return this.http.post<T>('/oauth/token', params.toString(), {
headers,
observe: 'response'
});
}
public logout<T>() {
this.http.post('/oauth/revoke_token', '', {}).subscribe();
}
getToken(): string {
return localStorage.getItem(TOKEN_NAME);
}
isTokenExpired(token?: string): boolean {
if(!token) token = this.getToken();
if(!token) return true;
const date = helper.getTokenExpirationDate(token);
console.log(date);
if(date === undefined) return false;
return !(date.valueOf() > new Date().valueOf());
}
}
下面是我的错误拦截器:
@Injectable()
export class H401Interceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
// this.authService.logout();
// location.reload(true);
localStorage.removeItem('currentUser');
}
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
}
答案 0 :(得分:0)
您可以使用HttpInterceptor,当后端回答“ 401未经授权”时,您将删除令牌并导航到登录页面。这是一个工作代码:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.storageService.retrieve(tokenKey)}`,
'Content-Type': 'application/json'
}
});
return next.handle(request).pipe(
catchError(
(err, caught) => {
if (err.status === 401){
this.handleAuthError();
return of(err);
}
throw err;
}
)
);
}
private handleAuthError() {
this.storageService.delete(tokenKey);
this.router.navigateByUrl('signIn');
}