【发布时间】:2022-01-23 16:04:30
【问题描述】:
我正在尝试用 express 后端和 jwt 和 angular 作为前端 构建一个应用程序。
问题是我需要识别登录到应用程序的用户,以将他们重定向到各自的面板。 每个用户的类型在数据库中的一个字段中找到(如果是普通用户和管理员则为空)。
问题是,我应该实施什么来识别用户?
这是登录名,应在此处识别用户。
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