【问题标题】:how to implement CanActivate in angular 5 using angular2-jwt?如何使用 angular2-jwt 在 Angular 5 中实现 CanActivate?
【发布时间】:2018-12-19 05:19:28
【问题描述】:

我正在尝试实现canActivate 类来控制对网址的访问。 为了加载令牌,我使用了这些函数:

saveToken(jwt:string){
    this.jwtToken = jwt;
    localStorage.setItem('token',jwt);
    let jwtHelper = new JwtHelper();
    this.roles = jwtHelper.decodeToken(this.jwtToken).roles;
}

loadToken(){
    this.jwtToken = localStorage.getItem('token');
}

在每个函数中,我都将标题添加为:

updateUser(appuser: AppUser) {
    return this.http.put('http://localhost:8080/users/' + appuser.id , appuser,{headers: new HttpHeaders({'Authorization':this.jwtToken})});
}

现在我想控制访问。有谁知道如何实施?不使用网址?

【问题讨论】:

    标签: angular jwt


    【解决方案1】:

    所以要实现canActivate,你需要制作一个AuthGuard。

    什么是 AuthGuard: 它确保用户是否通过身份验证以访问特定 URL。

    在这里,我创建了一个示例代码,以便您了解实现警卫的想法。

    我创建了一个服务。在其中,有一种方法isAuthenticated 检查令牌,如果令牌可用,则返回真,否则返回假。

    我在警卫内部使用了那个服务方法。

    在路由中,我设置了我的守卫来处理是否激活该路由。

    auth.service.ts

    import { Injectable } from '@angular/core';
    import { JwtHelper } from '@auth0/angular-jwt';
    
    @Injectable()
    export class AuthService {
    
      constructor(public jwtHelper: JwtHelper) {}
    
      // ...
      public isAuthenticated(): boolean {
    
        const token = localStorage.getItem('token');
    
        // Check whether the token is expired and return
        // true or false
        return !!token; (will return either true or false based on the token availability)
      }
    
    }
    

    auth-guard.service.ts

    import { Injectable } from '@angular/core';
    import { Router, CanActivate } from '@angular/router';
    import { AuthService } from './auth.service';
    
    @Injectable()
    export class AuthGuardService implements CanActivate {
    
      constructor(public auth: AuthService, public router: Router) {}
    
      canActivate(): boolean {
        if (!this.auth.isAuthenticated()) {
          this.router.navigate(['login']);
          return false;
        }
        return true;
      }
    
    }
    

    app.routes.ts

    import { Routes, CanActivate } from '@angular/router';
    import { ProfileComponent } from './profile/profile.component';
    import { AuthGuardService as AuthGuard } from './auth/auth-guard.service';
    
    export const ROUTES: Routes = [
      { path: '', component: HomeComponent },
      { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
      { path: '**', redirectTo: '' }
    ];
    

    更多:

    https://codecraft.tv/courses/angular/routing/router-guards/

    https://ryanchenkie.com/angular-authentication-using-route-guards

    【讨论】:

    • 我应该将 AuthGuardService 和 AuthService 添加到 app.module.ts 中的提供程序吗?
    • 是的,您需要这样做。如果您使用的是 Angular 6,那么对于服务,只需在服务本身中添加 providedIn: "root"。同样,您需要将 AuthGuard 放入模块中。
    【解决方案2】:

    你从localStorage获取jwtToken,你可以在CanActivate()中使用localStorage

        if(localStorage.getItem('token') != null)
           return true;
        else{
           this.router.navigate(['login']);
           return false;
        }
    

    或者使用此处显示的服务Routing Decisions Based on Token Expiration 和 JWT

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 2019-02-21
      • 1970-01-01
      • 2018-11-27
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多