NET6 授权方式:简单/角色/策略
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"), // ... };
授权:简单
控制器级别
[Authorize] public class AccountController : Controller { public ActionResult Login() { } public ActionResult Logout() { } }
操作(Action)级别
public class AccountController : Controller { public ActionResult Login() { } [Authorize] public ActionResult Logout() { } }
授权:角色
角色叠加:控制器 + 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"; } }
授权:策略
注册
builder.Services.AddAuthorization(options => { // 策略1:声明中一定要有 ClaimTypes.Role options.AddPolicy("policy1", policy => policy.RequireClaim(ClaimTypes.Role)); // 策略2:声明中一定要有 ClaimTypes.Role,且,值要包含:"admin", "user" options.AddPolicy("policy2", policy => policy.RequireClaim(ClaimTypes.Role, "admin", "user")); });
使用
[ApiController, Route("api/policy")] public class PolicyController : ControllerBase { /// <summary> /// Policy1 /// </summary> /// <returns></returns> [HttpGet, Route("policy1"), Authorize(Policy = "policy1")] public ActionResult<string> Policy1() { return "Policy1"; } /// <summary> /// Policy2 /// </summary> /// <returns></returns> [HttpGet, Route("policy2"), Authorize(Policy = "policy2")] public ActionResult<string> Policy2() { return "Policy2"; } }