使用AuthGuard的Angular8 canActivate方法中的API验证令牌 [英] Verify token with API in Angular8 canActivate method of AuthGuard

查看:34
本文介绍了使用AuthGuard的Angular8 canActivate方法中的API验证令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对某些路由的每个刷新请求进行一些验证.所以我正在使用Angular AuthGuard .问题出在我要使用在线API进行验证的 canActivate 方法中.

I want to do some validation on each refresh request for some routes. So I'm using Angular AuthGuard. The problem is in canActivate method I want to perform validation with online API.

API是/token/verify ,它仅获取 token 变量(jwt)并验证其正确与否.然后,如果验证未完成,则将路由到/login 页面,否则执行其余操作.

API is /token/verify which simply gets token variable (jwt) and verify if it's true or false. Then if verify is not complete will route to /login page else do the rest.

这是代码:

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
let token = this.auth.getToken();
let url = '/token/verify/';
if (!token) {
  this.router.navigate(['/login']);
  return false;
}
this.auth.verifyToken().then(res => {
  return true;
}).catch(err => {
  this.router.navigate(['/login']);
  return false;
})

verifyToken 方法是这样的:

verifyToken(): Promise<boolean> {
    let token = this.getToken();
    return !token ?
        new Promise<boolean>(resolve => {
            resolve(false);
            return false;
        }) :
        this.http.post(this.url + '/token/verify/', { 'token': token })
            .toPromise()
            .then((res) => {
                localStorage.data = JSON.stringify(res);//(res.json());
                return true;
            }
            ).catch((error) => {
                return false
            });
}

问题 promise 调用不起作用,将被传递.我的意思是从本地存储进行检查的第一部分工作正常.但是,使用在线API对其进行检查的下一部分将无法正常工作.并且 authGuard 不等待其响应进行路由.

Problem is that the promise call doesn't work and will be passed. I mean the first part that does check it from localstorage works fine. But the next part that checks it with online API will not work. and authGuard doesn't wait for its response to do the routing.

我想应该以某种 async/await 方式进行.但是我做了一些测试,但没有一个起作用.如果有人能帮助我会很高兴.

I guess it should be in some async/await manner. But I did some tests and none of them worked. Will be glad if anyone could help me.

推荐答案

如果使用 Observable s,我认为您将能够简化整个实现.

I think you'll be able to simplify the whole implementation if you use Observables instead.

如果您确实考虑了该建议,则可以将您的 verifyToken 方法重构为:

If you do consider that proposal, then your verifyToken method could be refactored to this:

import { of, Observable } from 'rxjs';

verifyToken(): Observable<boolean> {
  const token = this.getToken();
  return token ? this.http
    .post(this.url + '/token/verify/', {
      'token': token
    })
    .pipe(
      tap(res => localStorage.data = JSON.stringify(res)),
      map(
        res => true,
        error => false
      )
    ) : of(false)
}

然后在Guard中,您只需执行以下操作:

And then in your Guard, you'd simply do this:

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable < boolean > | Promise < boolean > | boolean {
  const token = this.auth.getToken();
  const url = "/token/verify/";

  if (!token) {
    this.router.navigate(['/login']);
    return false;
  }

  return this.auth.verifyToken().pipe(
    catchError(err => {
      console.log('Handling error locally and rethrowing it...', err);
      this.router.navigate(['/login']);
      return of(false);
    })
  );

}


这是一个 工作演示 供您参考.

Here's a Working Demo for your ref.

这篇关于使用AuthGuard的Angular8 canActivate方法中的API验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆