Asp.net
Authorize Policy 屬性總是返回 403 禁止使用 .net core Identity 和 JwtBearerAuthentication
按照本指南,我能夠使用
Microsoft.AspNetCore.Identity.EntityFrameworkCore Microsoft.AspNetCore.Authentication.JwtBearer現在我正在嘗試使用角色或聲明來保護我的 api 端點。我都試過了,結果相同(403)
使用
[Authorize]效果很好。我的程式碼目前看起來像這樣:
控制器:
[Authorize(Policy = "RequireUserRole")] // Also tried [Authorize(Roles="User")] public string Get() { return "YO"; }啟動:
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationContext>(); services.Configure<JWTSettings>(Configuration.GetSection("JWTSettings")); services.AddAuthorization(options => { options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User")); });…
app.UseIdentity(); var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value; var issuer = Configuration.GetSection("JWTSettings:Issuer").Value; var audience = Configuration.GetSection("JWTSettings:Audience").Value; var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)); app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = issuer, // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = audience, ValidateLifetime = true } }); app.UseMvcWithDefaultRoute();當我創建使用者時,我將其分配給角色“使用者”
await _userManager.AddToRoleAsync(user, "User");角色關係創建成功,但在到達端點時對角色的驗證失敗。
任何幫助表示讚賞!
答案在這篇mdsn 部落格文章中:
基於角色的授權可通過 ASP.NET Identity 開箱即用。只要用於身份驗證的不記名令牌包含角色元素,ASP.NET Core 的 JWT 不記名身份驗證中間件就會使用該數據為使用者填充角色。
因此,基於角色的授權屬性(如
$$ Authorize(Roles = “Manager,Administrator”) $$限制對經理和管理員的訪問)可以添加到 API 並立即工作。
所以我在我的訪問令牌對像中添加了一個名為角色的元素:
private string GetAccessToken(string userRole) { var payload = new Dictionary<string, object> { ... { "roles", userRole } }; return GetToken(payload); }