D.W*_*D.W 9 c# asp.net entity-framework-core .net-core asp.net-core
我有一个带有基本 jwt 身份验证和基于角色的授权的 Web api。现在我想限制某些字段被角色 user 中的用户编辑,因为基于路由的授权是不够的。
class Account {
public int Id {get; set;}
public string Email {get; set;}
public string Password {get; set;}
public bool Enabled {get; set;} // <- this field should only be editable by an admin or manager
public int RoleId {get; set;} // <- this field should only be editable by an admin
}
Run Code Online (Sandbox Code Playgroud)
当用户处于用户角色时,他只能更改他的电子邮件地址和密码,但仅限于他的帐户。当他处于角色管理器中时,他应该能够编辑电子邮件、密码和启用字段,但仅限于用户角色中的帐户。管理员可以编辑每个用户的每个字段。
有什么可以解决我的问题,例如:
class Account {
public int Id {get; set;}
public string Email {get; set;}
public string Password {get; set;}
[Authorize(Roles = "Admin,Manager")]
public bool Enabled {get; set;} // <- this field should only be editable by an admin or manager
[Authorize(Roles = "Admin")]
public int RoleId {get; set;} // <- this field should only be editable by an admin
}
Run Code Online (Sandbox Code Playgroud)
有关我的项目的更多信息: - ASP.NET Core 3.1 - 我将 Entity Framework Core 与 Postgres 数据库结合使用 - 对于身份验证,我使用基本的 jwt 持有者身份验证
所以,我认为您对 Authtorize 工作的理解不正确。
该属性用于控制器。您可以创建多个控制器,并为每个方法设置不同的角色来指定哪些角色可以调用该方法。
在 Dto(数据传输对象)类上指定它是不正确的。
但是您可以使用 2 个控制器和继承来制定一些有趣的解决方案。
//Account dto for edit
class AccountEditDto {
public int Id {get; set;}
public string Email {get; set;}
public string Password {get; set;}
}
//Controller to edit account
[Route("all/account_controller")]
public class AccountController : Controller
{
public ActionResult EditAccount(AccountEditDto accountDto)
{
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
然后对于创建经理角色设置如下:
//Account dto for edit
class AccountManagerEditDto : AccountEditDto {
public bool Enabled {get; set;}
}
//Controller admin to edit account
[Area("Manager")]
[Route("manager/account_controller")]
public class AccountManagerController : AccountController
{
[Authorize(Roles = "Manager")]
public ActionResult EditAccount(AccountManagerEditDto accountDto)
{
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)
然后创建管理员角色设置如下:
//Account dto for edit
class AccountAdminEditDto : AccountManagerEditDto {
public int RoleId {get; set;}
}
//Controller admin to edit account
[Area("Admin")]
[Route("admin/account_controller")]
public class AccountAdminController : AccountController
{
[Authorize(Roles = "Admin")]
public ActionResult EditAccount(AccountAdminEditDto accountDtp)
{
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用 URL 模式来调用控制器方法:
http://localhost/{role}/accont_controller/edit
Run Code Online (Sandbox Code Playgroud)
jwt是基于令牌的,这意味着每个用户都有其唯一的令牌,他使用该令牌来访问您的系统。
实现此目的的最简单方法是解码令牌并检查角色,从而使您能够为用户设置特定于角色的操作。
您将无法通过属性来执行此操作,因为jwt不支持它们。有一个很好的指南可以引导您完成它,因为这里的答案太长了:
它需要对代币如何工作有基本的了解,并且指南提供了简短的解释。
| 归档时间: |
|
| 查看次数: |
1561 次 |
| 最近记录: |