asp.net 自定义声明在AuthorizationHandlerContext Identity server 4 JWT中不可访问

vhmi4jdf  于 2023-04-08  发布在  .NET
关注(0)|答案(1)|浏览(157)

我有一个配置文件服务,它将声明添加到令牌

配置文件服务

public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);

            var claims = new List<Claim>();

            var userClaims = await _userManager.GetClaimsAsync(user);
            foreach (var userClaim in userClaims)
            {
                claims.Add(new Claim(userClaim.Type, userClaim.Value));
            }

            context.IssuedClaims.AddRange(claims);
        }

JWT Token

{
  "nbf": 1608909669,
  "exp": 1608996069,
  "iss": "https://localhost:5001",
  "aud": "https://localhost:5001/resources",
  "client_id": "Local",
  "sub": "307f4f24-71a5-4aee-8505-f87b58a1eb2e",
  "auth_time": 1608908167,
  "idp": "local",
  "IdentityServer": [
    "Read",
    "Create",
    "Update",
    "Delete"
  ],
  "Product": [
    "Read",
    "Create",
    "Update",
    "Delete"
  ],
  "jti": "87FA14C0153AD10D0E16A721720D19DB",
  "sid": "C739A377659C364AA29040FEE2FB4FA2",
  "iat": 1608909669,
  "scope": [
    "openid",
    "profile",
    "email"
  ],
  "amr": [
    "pwd"
  ]
}

只能在AuthorizationHandlerContext中获取以下声明

StartUp.cs

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                // base-address of your identityserver
                options.Authority = configuration.GetSection("IdentityServer:OAuth:AuthorizationUrl").Value;

                // name of the API resource
                options.ApiName = AuthorizePolicy.apiScope;
            });

app.UseAuthentication();

为什么我无法访问IdentityServer , Product声明。我使用的是Identity Server 4最新版本

更新1

在帐户控制器的登录过程中添加以下代码

var principal = await _claimsFactory.CreateAsync(user);
            var claims = principal.Claims.ToList();

            var isuser = new IdentityServerUser(user.Id)
            {
                DisplayName = user.UserName,
                AdditionalClaims = claims    
            };

            await HttpContext.SignInAsync(isuser, props);

现在用户包含所有额外的声明,但是如果我删除其中一个声明,JWT令牌会刷新,但是,用户标识仍然包含旧值,要刷新标识,我需要显式地再次登录用户,这是不合适的,我如何解决这个问题?

qf9go6mv

qf9go6mv1#

默认情况下,自定义声明不会包含在用户中,相反,您需要手动Map您关心的传入声明。
通常,您会添加以下内容:

public void ConfigureServices(IServiceCollection services)
{
    // By default, Microsoft has some legacy claim mapping that converts
    // standard JWT claims into proprietary ones. This removes those mappings.
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

然后在AddOpenIDConnect选项中,设置:

options.ClaimActions.MapUniqueJsonKey("website", "website");
options.ClaimActions.MapUniqueJsonKey("gender", "gender");
options.ClaimActions.MapUniqueJsonKey("birthdate", "birthdate");

交替地

options.ClaimActions.MapAllExcept("iss", "nbf", "exp", "aud", "nonce");

相同的配置可能如下所示:

}).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");

                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";
            });

如果您不想处理令牌并在那里添加声明,那么另一种方法是在您的授权策略中查找其他用户详细信息。请参阅有关Custom Authorization Policies的页面了解更多详细信息。
为了补充这个答案,我写了一篇博客文章,更详细地介绍了这个主题:Debugging OpenID Connect claim problems in ASP.NET Core

相关问题