Asp.net-Core
授權角色/策略屬性在 .Net Core 3 中不起作用
我沒有運氣在 .Net Core 3 中獲得任何角色或策略屬性。我從帶有身份驗證的 .Net Core Angular 入門項目開始我的項目。我認為這與新的 .AddDefault 方法有關,所以我盡可能地簡化了它,但它仍然不起作用。
這是我的政策:
services.AddAuthorization(options => { options.AddPolicy("IsAdmin", policy => policy.RequireClaim("role", "admin")); });這是我的控制器:
[Authorize(Policy = "IsAdmin")] [Route("api/[controller]")] public class AdminController : Controller { ...我創建了一個自定義配置文件服務,將聲明添加到令牌中,
var claims = new List<Claim>(); if (await _userManager.IsInRoleAsync(user, "Admin")) { claims.Add(new Claim(JwtClaimTypes.Role, "admin")); } context.IssuedClaims.AddRange(claims);在我的訪問令牌中(來自 jwt.io):
配置服務的其他部分:
services.AddDefaultIdentity<ApplicationUser>() .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); ... services.AddAuthentication() .AddIdentityServerJwt();普通
[Authorize]標籤與其他控制器上的訪問令牌一起工作正常。當我用訪問令牌點擊這個控制器時,我得到了一個
403響應我錯過了什麼阻止它工作?
我嘗試了您的程式碼,發現
role聲明密鑰已轉換為標準 Role ClaimsType:http://schemas.microsoft.com/ws/2008/06/identity/claims/role所以使用
ClaimTypes.Role將解決問題:services.AddAuthorization(options => { options.AddPolicy("IsAdmin", 策略 => { policy.RequireClaim( **ClaimTypes.Role** ,"admin"); }); });展示


