如何使用angular2-jwt在角度5中实现CanActivate?

时间:2018-07-11 08:36:41

标签: angular jwt

我正在尝试实现canActivate类来控制对url的访问。 为了加载令牌,我正在使用以下功能:

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})});
}

现在,我要控制访问权限。有人知道如何实现吗?不使用网址?

2 个答案:

答案 0 :(得分:3)

因此,要实现canActivate,您需要制作一个AuthGuard。

什么是AuthGuard::它可以确保用户是否通过了访问特定URL的认证。

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

我创建了一项服务。在其内部,有一种方法isAuthenticated用于检查令牌,如果令牌可用,则它将返回true,否则返回false。

我在警卫队内部使用了该服务方法。

在路由中,我放了我的后卫,它将处理是否激活该路由。

  

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

答案 1 :(得分:0)

您从localStorage获得了jwtToken,只需在CanActivate()中使用localStorage

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

或通过JWT使用此处Routing Decisions Based on Token Expiration所示的服务