ASP.Net Web Api 4.5.2使用UseJwtBearerAuthentication,忽略角色

时间:2017-09-17 19:52:25

标签: asp.net authorization jwt owin role

我想在Azure AD中使用角色。  我几乎所有工作都在运行,包括在AppRegistration Manifest中配置的角色等。在断点上,我确实看到了声明“角色”:[“MyAdminRole”]

我正在尝试对ApiController方法应用授权:

[System.Web.Http.Authorize("Roles="MyAdminRole")]
public void PostMyMethod(){}

owin初创公司看起来像这样:

    var issuer = "https://sts.windows.net/MyAzureAppServiceGuidFromAuthProperties/";
    var secret = TextEncodings.Base64Url.Decode("AzureAppServiceAuthSecret");  //have tried using the encoded value of my Azure Secret here as well
    app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { "MyAppIdGUID"},
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
            },
            TokenValidationParameters = new TokenValidationParameters
            {
                //this should set ClaimsIdentity.RoleClaimType to "roles", so it finds the "roles" claim during ClaimsPrincipal.UserInRole("")
                //in the Mvc Controller example, it behaves this way, but in my ApiController, this is being ignored.
                RoleClaimType = "roles"  
            }
        });

该请求来自Angular-adal应用程序,并包含授权:Bearer JWT_TOKEN。该令牌在https://jwt.io上进行解码,但即使我从AppService / Auth / AzureAD属性输入我的Azure应用程序的秘密,它也会显示“无效签名”。在解码后的令牌中,我确实看到了观众和发行人是我的期望,我看到“角色”声称拥有[“MyAdminRole”]。

在方法的断点上,如果我检查私有m_identities

((List<ClaimsIdentity>)typeof(System.Security.Claims.ClaimsPrincipal).GetField("m_identities", System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.GetField|System.Reflection.BindingFlags.Instance).GetValue(User))[0]

ClaimIdentity.RoleClaimType值等于System.Security.Claims.ClaimTypes.Role,即:“http://schemas.microsoft.com/ws/2008/06/identity/claims/role”,User.IsInrole(“MyAdminRole”)返回false,大概是因为User.Claims角色键是“角色”,即:它们不匹配。

相比之下,在使用控制器方法中断点的jmprieur的azure示例active-directory-dotnet-webapp-roleclaims(https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-roleclaims/)(使用OpenIdConnectAuthenticationOptions)时,ClaimsIdentity.RoleClaimType的值为“roles” “和User.IsInRole(”MyAdminRole“)返回true,可能是ClaimsPrincipal.IsInRole正在查找”角色“声明,因为ClaimsIdentity.RoleClaimType”roles“匹配”roles“的User.Claims键。

如何将ClaimsIdentity.RoleClaimType设置为“roles”,以使ClaimsIdentity.IsInRole(“MyAdminRole”)返回true,以便Authorize(“MyAdminRole”)通过?是JwtBearerAuthentication没有构建ClaimsPrinciple,还有其他东西,并且有什么东西将ClaimsIdentity.RoleClaimType设置为“http://schemas.microsoft.com/ws/2008/06/identity/claims/role”?而且,我如何知道app.useJwtBearerAthentication是否应用于请求?我没有看到任何可以记录它被调用的事件。

0 个答案:

没有答案