oauth2.0 令牌中缺少“角色”声明- NET CORE 3.1和IS 4

mpbci0fu  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(175)

我有一个服务,负责对用户进行身份验证。
更新后:

  • IdentityServer 4从2.3.2到4.0.2;

一个问题出现了:

  • 令牌不再包含所需的用户声明。

服务的配置方式如下:

  • Startup.cs包含:
applicationBuilder.UseCookiePolicy();
applicationBuilder.UseIdentityServer();
applicationBuilder.UseAuthorization();
//...
mvcCoreBuilder.AddAuthorization(ConfigureAuthorization);
var auth = mvcCoreBuilder.Services.AddAuthentication(ConfigureAuthenticationOptions);
auth.AddIdentityServerAuthentication(ConfigureIdentityServerAuthentication);
//...
void ConfigureAuthenticationOptions(AuthenticationOptions authenticationOptions)
{
    authenticationOptions.DefaultScheme = IdentityServerConstants.DefaultCookieAuthenticationScheme;
}
//...
void ConfigureAuthorization(AuthorizationOptions authorizationOptions)
{
    var requirements = new List<IAuthorizationRequirement> { new DenyAnonymousAuthorizationRequirement() };
    var schemes = new List<string> { IdentityServerConstants.DefaultCookieAuthenticationScheme };
    authorizationOptions.DefaultPolicy = new AuthorizationPolicy(requirements, schemes);
}
  • 设置cookie的登录控制器(针对IS 4 4.0.2更新)包含:
props = new _AuthenticationProperties
{
    IsPersistent = true,
    ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration),
};

// user.Claims contains the "role" claim

var claimsIdentity = new ClaimsIdentity(user.Claims, CookieAuthenticationDefaults.AuthenticationScheme);
claimsIdentity.AddClaim(new Claim(JwtClaimTypes.Subject, user.SubjectId));
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

// The created claimsPrincipal contains the "role" claim

await HttpContext.SignInAsync(claimsPrincipal, props);
  • 在更新IS 4之前,控制器看起来像这样:
await HttpContext.SignInAsync(user.SubjectId, props, user.Claims.ToArray());

在受保护的API项目中:

  • 当尝试验证控制器请求时,我有(在不同的API项目中):
// attribute for validating roles on controllers
[AuthorizeRoles(Role.SimpleRole)] // which implements IAuthorizationFilter

// And the implementation:
public void OnAuthorization(AuthorizationFilterContext context)
{
    var user = context.HttpContext.User;
    // user is of type 'ClaimsIdentity'
    // and it does not contain the "role" claim
 
    // some checks to verify the user here...
}

受保护的API项目的启动包含:

builder.AddAuthorization(ConfigureAuthorization);

var auth = builder.Services.AddAuthentication(ConfigureAuthenticationOptions);

auth.AddIdentityServerAuthentication(ConfigureIdentityServerAuthentication);

ConfigureIdentityServerAuthentication方法设置了一些IdentityServerAuthenticationOptionsRoleClaimType没有被设置,因为它有一个默认值'role',这是预期的值。
IdentityServerAuthenticationOptions来自'IdentityServer4.AccessTokenValidation'包版本3.0.1。
下面是两个截图来证明设置了RoleClaimType

  • 在Startup.cs上的授权服务上:

  • AuthorizeRoles属性的OnAuthorization方法上:

问题:

  • 为什么令牌不包含添加到ClaimsIdentity对象的所有声明?
  • 如何解决这个问题,以便令牌再次包含“角色”声明?

涉及的技术:

  • 网络核心3.1
  • IdentityServer4 4.0.2
sz81bmfz

sz81bmfz1#

默认情况下,IdentityServer和ASP.NET核心对RoleClaim的名称有不同的看法。
在您的客户端中添加此代码以修复该Map(设置TokenValidationParameters选项)

services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.LoginPath = "/User/Login";
            options.LogoutPath = "/User/Logout";
            options.AccessDeniedPath = "/User/AccessDenied";
        }).AddOpenIdConnect(options =>
        {
            options.Authority = "https://localhost:6001";
            options.ClientId = "authcodeflowclient";
            options.ClientSecret = "mysecret";
            options.ResponseType = "code";

            options.Scope.Clear();
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("email");
            options.Scope.Add("employee_info");

            //Map the custom claims that should be included
            options.ClaimActions.MapUniqueJsonKey("employment_start", "employment_start");
            options.ClaimActions.MapUniqueJsonKey("seniority", "seniority");
            options.ClaimActions.MapUniqueJsonKey("contractor", "contractor");
            options.ClaimActions.MapUniqueJsonKey("employee", "employee");
            options.ClaimActions.MapUniqueJsonKey("management", "management");
            options.ClaimActions.MapUniqueJsonKey(JwtClaimTypes.Role, JwtClaimTypes.Role);

            options.SaveTokens = true;
            options.SignedOutRedirectUri = "/";
            options.GetClaimsFromUserInfoEndpoint = true;


            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = JwtClaimTypes.Name,
                RoleClaimType = JwtClaimTypes.Role,

            };

            options.Prompt = "consent";
        });

此外,查看Fiddler中的各种请求有助于找出索赔问题。
将此设置为True也可以提供帮助:

options.GetClaimsFromUserInfoEndpoint = true;

为了补充这个答案,我写了一篇博客文章,更详细地讨论了这个主题:

相关问题