如何检查网页是否返回401?

问题描述 投票:0回答:1

我正在实现一项服务,此服务需要JWT令牌才能访问。

当下面的JWT令牌到期时,页面本身会显示。

<oauth>
<error_description>
Access token expired: <token_value>
</error_description>
<error>invalid_token</error>
</oauth> 

在角度我所有的路由是

{ path: '', component: HomeComponent }

例:

当我启动页面(本地 - https://localhost:8080/)时,我会得到令牌过期错误。我想将401捕获为页面加载。

那么如何检查当前页面是否返回401?例如,假设用户刷新页面如何获取401响应而不是在网页本身中显示。

angular jwt
1个回答
0
投票

我不确定我是否理解所有上下文,也不清楚是否可以从cookie中读取,如果你可以读取cookie,在HomeComponent中你可以有一个方法来检查cookie中的令牌是否过期了你调用需要令牌的服务(所以你不会得到401)

 import { CookieService } from 'ngx-cookie';
 @Component({
    selector: 'home-component',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
 })
 export class HomeComponent {
  tokenValid = true;
  constructor(public cookie: CookieService) {}

  ngOnInit(){
   this.tokenValid = this.isAccessTokenValid();
   if(this.tokenValid) {
     //call a service that uses the token
   }else {
     //do whatever
   }

  }

  isAccessTokenValid(): boolean {
   const acc_token = this.cookieService.get('token_in_cookie'); // use your key
   if (!!acc_token) {
     if (jwtService.isTokenExpired(acc_token)) {
       return false;
     }
     return true;
   } else {
   return false;
  }
 }

}

如果你需要的只是处理来自服务器的401,那么你可能需要按照上面的评论中的建议实现和拦截,类似......

@Injectable({
  providedIn: 'root'
})
export class HttpRequestInteceptorError implements HttpInterceptor {

 constructor() { }

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   return next.handle(req).pipe(catchError(err => {
     if (err instanceof HttpErrorResponse) {

      // Token expired
      if (err.status === 401) {
        // refresh access_token or whatever
      }
    }
    return throwError(err);
  }));
 }
}

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.