首页 > 解决方案 > Angular 6:如何使用身份验证服务实现路由保护

问题描述

如何在路由保护中使用来自 auth.service.ts 的数据。从 auth.service.ts 我使用验证令牌 API 来检查有效性(在邮递员返回 {"valid" : true} 中测试)。但我不明白如何使用路由保护来实现。

auth.service.ts 验证令牌的代码。如果令牌有效返回 true

 verifyToken(id:string, token: string) {
    const params = new HttpParams().set('a', id).set('b', token);

    this.base_url = environment.MYAPI_REST_API_URL;

    this.customersObservable = this.httpClient.get(this.base_url +'/registration/application/verifyConfirmationToken', {params});

     this.data = JSON.stringify(this.customersObservable);

     return this.data;
}

路由守卫代码

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.route.queryParams.subscribe(params => {
        this.id = params['a'];
        this.token = params['b'];
    });

    if (this.auth.verifyToken(this.id,this.token)) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    // window.location.href='http://www.cnn.com/';
    return false;
}

标签: angularangular5angular6

解决方案


是的,您可以通过创建 Auth Guard 服务来做到这一点。

// Auth Gaurd Service
// In AuthGaurdService

@Injectable()
class CanTokenActive implements CanActivate {
  constructor(private currentUser: UserToken) {}
 
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    // Logic to check token is exist or not.
  }
}


// In routhing module

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'home',
        component: Home,
        canActivate: ['canTokenActive']
      }
    ])
  ]
 })
class AppModule {}


推荐阅读