【问题标题】:how to implement different roles in an angular application with JWT如何使用 JWT 在 Angular 应用程序中实现不同的角色
【发布时间】:2022-01-23 16:04:30
【问题描述】:

我正在尝试用 express 后端和 jwtangular 作为前端 构建一个应用程序。

问题是我需要识别登录到应用程序的用户,以将他们重定向到各自的面板。 每个用户的类型在数据库中的一个字段中找到(如果是普通用户和管理员则为空)。

问题是,我应该实施什么来识别用户?

这是登录名,应在此处识别用户。

login(){
const user ={
  Email: this.UsuarioForm.get('Email')?.value,
  Password : this.UsuarioForm.get('Password')?.value
  }

  if(this.UsuarioForm.valid){
    this.userService.login(user).subscribe((data)=>{
      this.authService.setLocalStorage(data);
      console.log(data);
    },
    (error) =>{
      console.log(error);
    },

    ()=>{
      console.log('done!');
      this.router.navigate(['protected']);
    }
  );

}

}

这是他们目前采取的“受保护”路线。在这里我可以通过服务器的响应状态来识别用户,但我不知道这是否是最好的方法。

ngOnInit(): void {
this.usersService.protected().subscribe((data)=>{
  this.message = data.message;
  console.log(data);
},
(error) =>{
  if(error.status === 403){
    this.message= 'you are not authorized'
  }

  if(error.status === 200){
    this.message = 'The user is registered'
    console.log(this.authService.getExpiration());
  }

  if(error.status === 201){
    this.message= 'The user is registered and is admin'
    console.log(this.authService.getExpiration());
  }
  console.log(error);
},

() =>{
  console.log('http request done!')
}

);

}

【问题讨论】:

  • 当你构建你的 JWT 时,你会添加一个角色或声明它,让你知道用户是否是管理员。方式因您的后端解决方案而异,但概念是相同的

标签: angular express jwt role-based


【解决方案1】:

您可以使用canActivate guard 来实现对路由的基于角色的访问。
首先,使用这个命令创建一个守卫ng generate guard yourRoleName
然后,您可以检查角色并在 CanActivate 方法中执行您的逻辑。
这是一个简单的例子:

import { Injectable } from "@angular/core";
import {
  CanActivate,
} from "@angular/router";

@Injectable({
  providedIn: "root",
})
export class YourRoleNameGuard implements CanActivate {
  canActivate() {
    const role = localStorage.getItem("role");
    if (role == "YourRoleName") {
      return true;
    }
    return false;
  }
} 

并在app-routing.module.ts中为您要保护的路由添加此保护

const routes: Routes = [
  {
    path: "/your-path",
    component: YourComponent,
    canActivate: [YourRoleNameGuard],
  },
]
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

你可以从here阅读更多关于guards的信息

【讨论】:

  • 谢谢!这正是我所需要的
  • 不客气 :)
猜你喜欢
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 2020-07-29
  • 2010-10-19
  • 2018-12-19
  • 2018-10-08
相关资源
最近更新 更多