[英]`[Authorize (Roles=“Role”)]` not working, User.IsInRole(“Role”) always false
[英]Azure Ad Returning Roles in Claims but User.IsInRole returns false
知道是什么原因造成的嗎? 我可以在 User.Claims 中看到聲明 我唯一能想到的是來自 Azure 廣告角色的聲明返回的內容與 IsInRole() 檢查的內容不同?
[Startup.Auth][3]
澄清一下,我正在找回角色,但我認為他們沒有被正確添加到聲明列表中,我無法弄清楚原因。 Nerith IsInRole 或 [Authorize(Roles="...")] 將正確檢查角色聲明。
這些變化中的任何一個都對我有用:
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
RoleClaimType = System.Security.Claims.ClaimTypes.Role
},
或
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
},
您需要指定包含角色的聲明類型的名稱。 像這樣:
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
RoleClaimType = "roles"
},
經過大量挖掘,我發現了我們的問題所在,其中一些答案是正確的,但前提是您尚未將應用服務配置為啟用 Azure AD。
如果您這樣做,將不會使用代碼中定義的 RoleClaimType 並將其設置為默認值“http://schemas.microsoft.com/ws/2008/06/identity/claims/role”,但您的所有角色聲明將是“角色”。
解決方案基本上是將聲明從“角色”復制到 ClaimsIdentity.RoleClaimType。 解決方案在這里找到並在上面提到。
解決方法:
public void ConfigureAuth(IAppBuilder app)
{
//This setting ensures that we use the specified TokenValidationParameters.RoleClaimType below
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
//Omitted some stuff
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
RoleClaimType = "roles"
}
}
);
//Configure out OnAuth Method to fix the roles post auth
app.Use((context, next) =>
{
OnAuth(context);
return next.Invoke();
});
app.UseStageMarker(PipelineStage.PostAuthenticate);
}
private static void OnAuth(IOwinContext context)
{
if (ClaimsPrincipal.Current.Identity.IsAuthenticated)
{
var claimsPrincipal = ClaimsPrincipal.Current;
var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;
var appRoles = new List<Claim>();
//local dev will be right
if (claimsIdentity.RoleClaimType == "roles")
return;
//Find all the claims with "roles" and add a copy claim with the correct RoleClaimType.
foreach (Claim claim in claimsPrincipal.FindAll("roles"))
appRoles.Add(new Claim(claimsIdentity.RoleClaimType, claim.Value));
if (appRoles.Count > 0)
claimsIdentity.AddClaims(appRoles);
}
}
如果您遇到與我相同的問題,我創建了一個自定義 AuthorizeAttribute 類,但忘記覆蓋 AuthorizeCore 函數。 添加下面的代碼為我解決了這個問題。
//Core authentication, called before each action
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return base.AuthorizeCore(httpContext);
}
Add Validate Issuer= false;
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
NameClaimType = "name",
RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.