简体   繁体   English

AuthorizationHandlerContext 身份服务器中无法访问自定义声明 4 JWT

[英]Custom claim not accessible in AuthorizationHandlerContext Identity server 4 JWT

I have a profile service that adds the claim to the token我有一个将声明添加到令牌的配置文件服务

Profile service档案服务

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 JWT 令牌

{
  "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"
  ]
}

Only able to get the below claim in the AuthorizationHandlerContext只能在AuthorizationHandlerContext中获得以下声明

在此处输入图像描述

StartUp.cs启动.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();

Why I am not able to access IdentityServer, Product claim.为什么我无法访问IdentityServer, Product声明。 I am using Identity server 4 latest version我正在使用 Identity server 4 最新版本

在此处输入图像描述

UPDATE 1更新 1

While adding the below code during the login process in the Account controller在帐户 controller 的登录过程中添加以下代码

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

Now the user contains all the additional claims, but if I remove one of the claims the JWT token is refreshed, however, the User Identity still contains the old value, to refresh the identity I need to explicitly login the user again which is not suitable, how can I fixed this?现在用户包含所有其他声明,但如果我删除其中一个声明 JWT 令牌被刷新,但是,用户身份仍然包含旧值,要刷新身份我需要再次显式登录用户,这是不合适的,我该如何解决这个问题?

by default custom claims will not be included in the User, instead you need to manually map the incoming claims that you care about.默认情况下,自定义声明不会包含在用户中,相反,您需要手动 map 您关心的传入声明。

Typically, you would add this:通常,您会添加以下内容:

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();

and then in the AddOpenIDConnect options, set:然后在 AddOpenIDConnect 选项中,设置:

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

alternatively或者

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

Same configuration could look like this:相同的配置可能如下所示:

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

If you don't want to deal with the tokens and add the claims there, then an alternative is to lookup additional user details in your authorization polices.如果您不想处理令牌并在那里添加声明,那么另一种方法是在您的授权策略中查找其他用户详细信息。 See this page about Custom Authorization Policies for more details.有关更多详细信息,请参阅有关自定义授权策略的此页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 声明为空,用户未在 AuthorizationHandlerContext 的 HandleRequirement 中通过 Duende 身份服务器进行身份验证 - Claims is empty and user is not Authenticated in HandleRequirement of AuthorizationHandlerContext with Duende identity server 没有从身份服务器获取用户“电子邮件”作为索赔(来自jwt令牌) - Not getting user “email” as a claim (from jwt token) back from identity server 来自自定义身份验证服务器的MVC前端身份JWT令牌 - MVC Frontend Identity JWT Token from custom Authentication server 在JWT Bearer的身份OnTokenValidated事件中插入更多声明 - Insert more claim into identity OnTokenValidated event of JWT Bearer 子声明缺少带有 Mongo DB 的 Identity Server 4 - sub claim is missing Identity Server 4 with Mongo DB ASP.NET身份和自定义声明的验证 - ASP.NET Identity and validation of a custom claim 如何在使用 Identity Server 授权的 aspnet 核心应用程序中访问自定义声明 - How to access custom claim in aspnet core application authorized using Identity Server Identity Server 4向已生成的令牌添加声明 - Identity Server 4 Add a claim to a generated token Identity Server部分登录并获得电子邮件声明 - Identity Server Partial Login and get the Email Claim 在身份服务器上检查JWT的有效性 - Check Validity of JWT on identity server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM