roc*_*k11 5 authentication jwt typescript angular
我正在制作一个使用 jwt 来验证 db 调用的角度应用程序。但是问题
是当令牌在服务器上过期时,应用程序开始提供空白页而不是数据,因为过期的令牌仍在本地存储中。经过一些研究我发现 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);
        }));
    }
}
ala*_*bid 11
您可以使用 HttpInterceptor,当后端回答“401 Unauthorized”时,您删除令牌并导航到登录页面。这是一个工作代码:
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');
  }
| 归档时间: | 
 | 
| 查看次数: | 13074 次 | 
| 最近记录: |