简单授权
以下代码限制为仅允许经过身份验证的用户访问 AccountController
:
[Authorize] public class AccountController : Controller { public ActionResult Login() { } public ActionResult Logout() { } }
如果要将授权应用于操作而不是控制器,请将 AuthorizeAttribute
属性应用于操作本身:
public class AccountController : Controller { public ActionResult Login() { } [Authorize] public ActionResult Logout() { } }
角色授权
jwt的Claims
// 1.定义需要使用到的Claims var claims = new List<Claim> { new Claim("Name", "UserName"), new Claim(ClaimTypes.Role, "Admin"), new Claim(ClaimTypes.Role, "admin"), //new Claim(ClaimTypes.Role, "user"), // ... };
角色叠加:控制器 + Action
/// <summary> /// 授权api - 角色:控制器有角色,必须要有user角色才能访问 /// jwt token角色的key必须用ClaimTypes.Role,且值和Roles区分大小写 /// </summary> [ApiController, Route("api/roleexists"), Authorize(Roles = "user")] public class RoleExistsController : ControllerBase { /// <summary> /// 与控制器的Authorize叠加作用,除了拥有user,还需拥有admin /// </summary> /// <returns></returns> [HttpGet, Route("getadminanduser"), Authorize(Roles = "admin")] public ActionResult<string> GetAdminAndUser() { return "GetAdminAndUser"; } }
角色多选一,满足一个就行
/// <summary> /// 授权api - 角色: 控制器存在授权角色 /// jwt token角色的key必须用ClaimTypes.Role,且值和Roles区分大小写 /// </summary> [ApiController, Route("api/rolenotexists")] public class RoleNotExistsController : ControllerBase { /// <summary> /// user 或 admin 其一满足即可 /// </summary> /// <returns></returns> [HttpGet, Route("getadminoruser"), Authorize(Roles = "user,admin")] public ActionResult<string> GetAdminOrUser() { return "GetAdminOrUser"; } }
标签:Authorize,角色,方式,ActionResult,Role,user,授权,NET6,public From: https://www.cnblogs.com/CRobot/p/18204671