如何将声明包含在从授权端点检索的访问令牌中? [英] How do I include claims into the Access Token retrieved from the Authorize endpoint?

查看:28
本文介绍了如何将声明包含在从授权端点检索的访问令牌中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在通过 IdSrv 进行身份验证时检索到的访问令牌中默认包含声明.Claim Ticket 应始终包含在访问令牌中,因此我创建了一个作为资源范围的新范围,并包含 Ticket 作为 ScopeClaim.但是,当 IdSrv 创建访问令牌并调用 GetProfileDataAsync 时,您可以从 IdSrv 日志中看到,上下文中请求的声明列表为空,因此没有向访问令牌添加声明.

如何在默认情况下将此声明包含在访问令牌中?

我的印象是请求 Resource 范围将允许范围中的声明作为访问令牌的一部分返回.

范围

 public static List得到(){返回新列表<范围>{StandardScopes.OpenId//处理open id connect时的标准范围,标准范围.离线访问,新范围{名称 = "应用程序",DisplayName = "应用程序",类型 = ScopeType.Identity,声明 = 新列表{新的范围声明{AlwaysIncludeInIdToken = false,名称 = "应用程序",描述 = "角色信息"},//新的范围声明//{//AlwaysIncludeInIdToken = false,//Name = "票",//说明 = "登录票"//}},IncludeAllClaimsForUser = false},新范围{Name = "AppAccess",DisplayName = "AppAccess",类型 = ScopeType.Resource,声明 = 新列表{新的范围声明{Name = "票",Description = "登录票",}},IncludeAllClaimsForUser = true}};

索赔

 公共静态列表<客户端>得到(){返回新列表<客户端>{新客户{ClientName = "混合流",ClientId = "apphybrid",启用 = 真,Flow = Flows.Hybrid,AllowAccessToAllScopes = 真,IdentityTokenLifetime = 120,AccessTokenLifetime = 400,RequireConsent = 假,ClientSecrets = new List{新的秘密(秘密".Sha256())},RedirectUris = new List{本地主机/应用程序/登录/登录.mr"},PostLogoutRedirectUris = new List{本地主机/应用程序/登录/登录.mr"},AllowedScopes = 新列表<字符串>{Constants.StandardScopes.OpenId,Constants.StandardScopes.OfflineAccess,应用程序",应用访问"}}};}

IDSrv 配置

public override Task AuthenticateLocalAsync(LocalAuthenticationContext context){var securityServiceProxy = new SecurityServiceProxy(new ServiceHeadersParameters { UserHostAddress = Ctx.Request.Host.Value });var ticket = securityServiceProxy.UseServiceClient(serviceClient => serviceClient.AuthenticateUser(context.UserName, context.Password, Configuration.ProviderCode));如果 (!ticket.IsValid()){context.AuthenticateResult = new AuthenticateResult("无效凭据");返回 Task.FromResult(0);}var claim = new List{新索赔(GlobalConstant.TicketClaim,ticket.Ticket.ToString())};context.AuthenticateResult = new AuthenticateResult(票证.UserObjId.ToString(),上下文.用户名,索赔:索赔,authenticationMethod: Constants.AuthenticationMethods.Password,身份提供者:Configuration.ProviderCode);返回 Task.FromResult(0);}公共覆盖任务 GetProfileDataAsync(ProfileDataRequestContext 上下文){var applicationDto = GetApplicationDto(context);var claim = new List{新索赔(常量.索赔类型.主题,上下文.主题.GetSubjectId()),};Log.Debug("请求的声明...");if (context.RequestedClaimTypes == null){Log.Debug("请求的声明为空");}别的{foreach (var x in context.RequestedClaimTypes){Log.Debug($"声明{x}");}如果(context.RequestedClaimTypes.Contains(GlobalConstant.TicketClaim))claim.Add(context.Subject.Claims.Where(x => x.Type.Equals(GlobalConstant.TicketClaim)).FirstOrDefault());如果 (context.RequestedClaimTypes.Contains(GlobalConstant.ApplicationClaim))claim.Add(new Claim(GlobalConstant.ApplicationClaim, applicationDto.Jsonify()));}//设置已发布的声明 - 这些是请求的声明(如果可用)context.IssuedClaims = 索赔;Log.Debug("完成 ProfileDataAsync");返回 Task.FromResult(0);}私有 ApplicationDto GetApplicationDto(ProfileDataRequestContext 上下文){var securityServiceProxy = new SecurityServiceProxy(new ServiceHeadersParameters { UserHostAddress = Ctx.Request.Host.Value });返回 securityServiceProxy.UseServiceClient(serviceClient => serviceClient.RetrieveAuthenticatedUser(GetUserTicketFromContext(context)));}私有静态 UserTicketDto GetUserTicketFromContext(ProfileDataRequestContext context){Log.Debug("上下文中的声明...");foreach(var x in context.Subject.Claims){Log.Debug($"Cliams {x.Type} {x.Value}");}var ticketString = context.Subject.Claims.Where(x => x.Type.Equals(GlobalConstant.TicketClaim)).FirstOrDefault()?.Value;var userIdString = context.Subject.GetSubjectId();向导票,用户 ID;if(Guid.TryParse(ticketString, out Ticket) && Guid.TryParse(userIdString, out UserId)){return new UserTicketDto { Ticket = Ticket, UserObjId = UserId };}返回新的 UserTicketDto();}

网页配置

 JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary();AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityModel.JwtClaimTypes.Name;app.Use(async (ctx, next) => { await next(); });app.UseCookieAuthentication(new CookieAuthenticationOptions){AuthenticationType = "cookies"});app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions){ClientId = OAuthConstant.Client,RedirectUri = "localhost/App/login/Login.mr",PostLogoutRedirectUri = "localhost/App/login/Login.mr",权限 = "localhost/Oauth2server/securetoken",SignInAsAuthenticationType = "Cookies",ResponseType = "令牌代码 id_token",Scope = "OpenId App offline_access AppAccess",ClientSecret = "秘密",UseTokenLifetime = false,通知 = 新 OpenIdConnectAuthenticationNotifications(){AuthorizationCodeReceived = IdentityServerClient.HandleOther,SecurityTokenReceived = IdentityServerClient.HandleOther,MessageReceived = IdentityServerClient.HandleOther,AuthenticationFailed = IdentityServerClient.HandleOther,RedirectToIdentityProvider = IdentityServerClient.HandleRedirectToIdentityProvider,SecurityTokenValidated = IdentityServerClient.HandleSecurityTokenValidated}});

日志

2016-06-15 12:04:51.943 -05:00 【信息】登录页面提交2016-06-15 12:04:55.320 -05:00 [信息] 用户服务成功验证登录凭据2016-06-15 12:04:55.332 -05:00 [信息] 在用户服务上调用 PostAuthenticateAsync2016-06-15 12:04:55.338 -05:00 [信息] 发布主要登录 cookie2016-06-15 12:04:55.344 -05:00 [信息] 重定向到:http://localhost/OAuth2Server/securetoken/connect/authorize?client_id=apphybrid&redirect_uri=http:%2F%2Flocalhost%2Fapp%2FLogin%2FLogin.mr&安培; response_mode = form_post&安培; RESPONSE_TYPE =代码id_token令牌安培;范围=应用的OpenID offline_access AppAccess&安培;状态= OpenIdConnect.AuthenticationProperties%3DebxFcJnjMiMq2m1gPqBsYlrBWdLct2kaJSYn-s0nxImnff-37i4t8Wa3wAJewJGFe9msgeeqJDKtR1gwwfA0e8Pdd6RNAi6YPo_CqT4l5zV8ifohYQVN9TrWfLXITXuKId9IW2cCeRQL6d8uWfkzSANqAGSbSGJYZ5pgOLULQresbAiJ7N77FgBmgrVtX4hDQuwGGL5vZFCb_C5tjl8_ezH12w8zQfifKuLwjaDmOSGYyo2AqpowQXXeSSSDgKBF&安培;随机数= 636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2ZjMtODdhYmIxYTM5Mjg52016-06-15 12:04:55.368 -05:00 [调试] 传入请求:/securetoken/connect/authorize2016-06-15 12:04:55.381 -05:00 [信息] 开始授权请求2016-06-15 12:04:55.381 -05:00 [信息] 开始授权请求协议验证2016-06-15 12:04:55.381 -05:00 [信息]授权请求验证成功"{"ClientId": "apphybrid","ClientName": "app Hybrid Flow","RedirectUri": "http://localhost/app/Login/Login.mr","AllowedRedirectUris": ["http://localhost/app/Login/Login.mr"],"SubjectId": "783bf872-b864-4042-853d-04fbcb7a505a","ResponseType": "code id_token token","ResponseMode": "form_post","流": "混合","RequestedScopes": "app openid offline_access appAccess", 国家": OpenIdConnect.AuthenticationProperties = ebxFcJnjMiMq2m1gPqBsYlrBWdLct2kaJSYn-s0nxImnff-37i4t8Wa3wAJewJGFe9msgeeqJDKtR1gwwfA0e8Pdd6RNAi6YPo_CqT4l5zV8ifohYQVN9TrWfLXITXuKId9IW2cCeRQL6d8uWfkzSANqAGSbSGJYZ5pgOLULQresbAiJ7N77FgBmgrVtX4hDQuwGGL5vZFCb_C5tjl8_ezH12w8zQfifKuLwjaDmOSGYyo2AqpowQXXeSSSDgKBF ","Nonce": "636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2Zjmx5mtdm","SessionId": "e79cd97a339b4513b45038e7755c1b88",生的": {"client_id": "apphybrid","redirect_uri": "http://localhost/app/Login/Login.mr","response_mode": "form_post","response_type": "code id_token token","scope": "app openid offline_access appAccess", 状态": OpenIdConnect.AuthenticationProperties = ebxFcJnjMiMq2m1gPqBsYlrBWdLct2kaJSYn-s0nxImnff-37i4t8Wa3wAJewJGFe9msgeeqJDKtR1gwwfA0e8Pdd6RNAi6YPo_CqT4l5zV8ifohYQVN9TrWfLXITXuKId9IW2cCeRQL6d8uWfkzSANqAGSbSGJYZ5pgOLULQresbAiJ7N77FgBmgrVtX4hDQuwGGL5vZFCb_C5tjl8_ezH12w8zQfifKuLwjaDmOSGYyo2AqpowQXXeSSSDgKBF ","nonce": "636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2ZjMx5MDYtMjYxYjkwMWEz}}"2016-06-15 12:04:55.399 -05:00 [信息] 创建混合流响应.2016-06-15 12:04:55.412 -05:00 [信息] 创建隐式流响应.2016-06-15 12:04:55.416-05:00 [调试] 创建访问令牌2016-06-15 12:04:55.424-05:00 [调试] 获取 ProfileDataAsync2016-06-15 12:04:55.436 -05:00 [调试] 上下文中的声明...2016-06-15 12:04:55.437 -05:00 [调试] Cliams sub 783bf872-b864-4042-853d-04fbcb7a505a2016-06-15 12:04:55.437 -05:00 [调试] Cliams 名称 dev.guser2016-06-15 12:04:55.437 -05:00 [调试] Cliams amr 密码2016-06-15 12:04:55.437 -05:00 [调试] Cliams idp IDSRV2016-06-15 12:04:55.437-05:00 [调试] Cliams auth_time 14660102952016-06-15 12:04:55.437 -05:00 [调试] Cliams 票 fc05cd84-7756-4ec5-ac3c-53ac6d4d5e2a2016-06-15 12:04:55.975 -05:00 [调试] requseted 索赔...2016-06-15 12:04:55.976 -05:00 [调试] 请求的声明为空2016-06-15 12:04:55.976-05:00 [调试] 完成 ProfileDataAsync2016-06-15 12:04:55.982 -05:00 [调试] 创建 JWT 访问令牌2016-06-15 12:04:56.049-05:00 [调试] 创建身份令牌2016-06-15 12:04:56.054 -05:00 [信息] 获取主题身份令牌的声明:783bf872-b864-4042-853d-04fbcb7a505a2016-06-15 12:04:56.054-05:00 [调试] 获取 ProfileDataAsync2016-06-15 12:04:56.066 -05:00 [调试] 上下文中的声明...2016-06-15 12:04:56.066 -05:00 [调试] Cliams sub 783bf872-b864-4042-853d-04fbcb7a505a2016-06-15 12:04:56.066 -05:00 [调试] Cliams 名称 dev.guser2016-06-15 12:04:56.066 -05:00 [调试] Cliams amr 密码2016-06-15 12:04:56.066 -05:00 [调试] Cliams idp IDSRV2016-06-15 12:04:56.066-05:00 [调试] Cliams auth_time 14660102952016-06-15 12:04:56.066 -05:00 [调试] Cliams 票 fc05cd84-7756-4ec5-ac3c-53ac6d4d5e2a2016-06-15 12:04:56.338 -05:00 [调试] requseted 索赔...2016-06-15 12:04:56.338 -05:00 [调试] Cliams sub2016-06-15 12:04:56.338-05:00 [调试] 完成 ProfileDataAsync2016-06-15 12:04:56.338-05:00 [调试] 创建 JWT 身份令牌2016-06-15 12:04:56.344 -05:00 [调试] 将客户端apphybrid"添加到主题783bf872-b864-4042-853d-04fbcb7a505a"的客户端列表cookie2016-06-15 12:04:56.349 -05:00 [信息] 结束授权请求2016-06-15 12:04:56.352 -05:00 [信息] 发布到 http://localhost/app/Login/Login.mr2016-06-15 12:04:56.352 -05:00 [调试] 使用 AssetManager 呈现授权响应 HTML2016-06-15 12:04:56.388 -05:00 [调试] 传入请求:/securetoken/assets/app.FormPostResponse.js//网页2016-06-15 12:04:56,422 [16] 调试 app.Web.IdentityServer.IdentityServerClient 触发 MessageReceivedNotification`2 通知2016-06-15 12:04:56,426 [16] 调试 app.Web.IdentityServer.IdentityServerClient 触发 SecurityTokenReceivedNotification`2 通知2016-06-15 12:04:56,487 [16] 调试 app.Web.IdentityServer.IdentityServerClient 触发 SecurityTokenValidated 通知2016-06-15 12:04:56,487 [16] 调试 app.Web.IdentityServer.IdentityServerClient 身份中的声明2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:iss http://localhost/OAuth2Server/securetoken2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:aud apphybrid2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:exp 14660104162016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:nbf 14660102962016年6月15日12:04:56488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient要求:随机数636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2ZjMtODdhYmIxYTM5Mjg52016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:iat 14660102962016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:at_hash 6pIu3P1cEeTQJMcK8Gcnhw2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:c_hash VsSw9HC0xyodlSkSCZefLw2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:side e79cd97a339b4513b45038e7755c1b882016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:sub 783bf872-b864-4042-853d-04fbcb7a505a2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:auth_time 14660102952016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:idp IDSRV2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 声明:amr 密码2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient 访问令牌:[省略]2016-06-15 12:04:56,488 [16] 调试 app.Web.IdentityServer.IdentityServerClient id 令牌:[省略]2016-06-15 12:04:56,491 [16] 调试 app.Web.IdentityServer.IdentityServerClient 触发 AuthenticationFailedNotification`2 通知//网页//日志

有问题的日志输出...

2016-06-15 12:04:55.412 -05:00 [信息] 创建隐式流响应.2016-06-15 12:04:55.416-05:00 [调试] 创建访问令牌2016-06-15 12:04:55.424-05:00 [调试] 获取 ProfileDataAsync2016-06-15 12:04:55.436 -05:00 [调试] 上下文中的声明...2016-06-15 12:04:55.437 -05:00 [调试] Cliams sub 783bf872-b864-4042-853d-04fbcb7a505a2016-06-15 12:04:55.437 -05:00 [调试] Cliams 名称 dev.guser2016-06-15 12:04:55.437 -05:00 [调试] Cliams amr 密码2016-06-15 12:04:55.437 -05:00 [调试] Cliams idp IDSRV2016-06-15 12:04:55.437-05:00 [调试] Cliams auth_time 14660102952016-06-15 12:04:55.437 -05:00 [调试] Cliams 票 fc05cd84-7756-4ec5-ac3c-53ac6d4d5e2a <- 有我想要的声明2016-06-15 12:04:55.975 -05:00 [调试] requseted 索赔...2016-06-15 12:04:55.976 -05:00 [Debug] Requested Claims Is Null <-但这需要表明我们想要那个声明......2016-06-15 12:04:55.976-05:00 [调试] 完成 ProfileDataAsync

解决方案

更新 2:好的,现在我仔细观察,你有 IncludeAllClaimsForUser = true.在 GetProfileData 中,上下文中有一个可比较的标志.我怀疑这就是为什么您在集合中没有声明的原因.

更新 1:应在 GetProfile 中而不是在 AuthentivcateLocal 方法中的 AuthenticateResult 中添加您想要进入令牌的声明.

原文:将范围类型从 Identity 更改为 Resource.这会影响声明进入哪些令牌.

I want to include a claim by default in the access token retrieved when I Authenticate via IdSrv. The Claim Ticket should always be included in the access token, as such I have created a new scope that is a resource scope and included Ticket as a ScopeClaim. However as you can see from the IdSrv logs when IdSrv is creating the access token and calls GetProfileDataAsync the list of requested claims in the context is empty, and so no claims are added to the access token.

How can I include this claim into the access token by default?

I was under the impression that requesting a Resource scope would allow the claims in the scope to be returned as part of the access token.

Scopes

        public static List<Scope> Get()
        {
            return new List<Scope>
            {
                StandardScopes.OpenId //standard scope when dealing with open id connect
                ,
                StandardScopes.OfflineAccess
                ,
                new Scope
                {
                    Name = "App",
                    DisplayName = "App",
                    Type = ScopeType.Identity,
                    Claims = new List<ScopeClaim>
                    {
                        new ScopeClaim
                        {
                            AlwaysIncludeInIdToken = false,
                            Name = "App",
                            Description = "Role Information"
                        },
//                        new ScopeClaim
//                        {
//                            AlwaysIncludeInIdToken = false,
//                            Name = "Ticket",
//                            Description = "Login ticket"
//                        }
                    },
                    IncludeAllClaimsForUser = false
                },
                new Scope
                {
                    Name = "AppAccess",
                    DisplayName = "AppAccess",
                    Type = ScopeType.Resource,
                    Claims = new List<ScopeClaim>
                    {
                        new ScopeClaim
                        {
                            Name = "Ticket",
                            Description = "Login ticket",
                        }
                    },
                    IncludeAllClaimsForUser = true
                }
            };

Claims

    public static List<Client> Get()
    {
        return new List<Client>
        {
            new Client
            {
                ClientName = "Hybrid Flow",
                ClientId = "apphybrid",
                Enabled = true,
                Flow = Flows.Hybrid,
                AllowAccessToAllScopes = true,
                IdentityTokenLifetime = 120,
                AccessTokenLifetime = 400,
                RequireConsent = false,
                ClientSecrets = new List<Secret>
                {
                    new Secret("secret".Sha256())
                },
                RedirectUris = new List<string>
                {
                    "localhost/App/login/Login.mr"
                },
                PostLogoutRedirectUris = new List<string>
                {
                    "localhost/App/login/Login.mr"
                },
                AllowedScopes = new List<string>
                {
                    Constants.StandardScopes.OpenId,
                    Constants.StandardScopes.OfflineAccess,
                    "App",
                    "AppAccess"
                }
            }
        };
    }

IDSrv Config

public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
        {
            var securityServiceProxy = new SecurityServiceProxy(new ServiceHeadersParameters { UserHostAddress = Ctx.Request.Host.Value });

            var ticket = securityServiceProxy.UseServiceClient(serviceClient => serviceClient.AuthenticateUser(context.UserName, context.Password, Configuration.ProviderCode));

            if (!ticket.IsValid())
            {
                context.AuthenticateResult = new AuthenticateResult("Invalid credentials");
                return Task.FromResult(0);
            }

            var claims = new List<Claim> {
                new Claim(GlobalConstant.TicketClaim, ticket.Ticket.ToString())
            };

            context.AuthenticateResult = new AuthenticateResult(
                ticket.UserObjId.ToString(),
                context.UserName,
                claims: claims,
                authenticationMethod: Constants.AuthenticationMethods.Password,
                identityProvider: Configuration.ProviderCode
                );

            return Task.FromResult(0);
        }

        public override Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var applicationDto = GetApplicationDto(context);

            var claims = new List<Claim>
            {
                new Claim(Constants.ClaimTypes.Subject, context.Subject.GetSubjectId()),
            };

            Log.Debug("The requested claims...");
            if (context.RequestedClaimTypes == null)
            {
                Log.Debug("Requested Claims is null");
            }
            else
            {
                foreach (var x in context.RequestedClaimTypes)
                {
                    Log.Debug($"Claims {x}");
                }

                if (context.RequestedClaimTypes.Contains(GlobalConstant.TicketClaim))
                    claims.Add(context.Subject.Claims.Where(x => x.Type.Equals(GlobalConstant.TicketClaim)).FirstOrDefault());

                if (context.RequestedClaimTypes.Contains(GlobalConstant.ApplicationClaim))
                    claims.Add(new Claim(GlobalConstant.ApplicationClaim, applicationDto.Jsonify()));
            }

            // set the issued claims - these are the ones that were requested, if available
            context.IssuedClaims = claims;
            Log.Debug("Finished ProfileDataAsync");
            return Task.FromResult(0);
        }

        private ApplicationDto GetApplicationDto(ProfileDataRequestContext context)
        {
            var securityServiceProxy = new SecurityServiceProxy(new ServiceHeadersParameters { UserHostAddress = Ctx.Request.Host.Value });

            return securityServiceProxy.UseServiceClient(serviceClient => serviceClient.RetrieveAuthenticatedUser(GetUserTicketFromContext(context)));
        }

        private static UserTicketDto GetUserTicketFromContext(ProfileDataRequestContext context)
        {
            Log.Debug("The claims in the context...");
            foreach(var x in context.Subject.Claims)
            {
                Log.Debug($"Cliams {x.Type} {x.Value}");
            }

            var ticketString = context.Subject.Claims.Where(x => x.Type.Equals(GlobalConstant.TicketClaim)).FirstOrDefault()?.Value;
            var userIdString = context.Subject.GetSubjectId();

            Guid Ticket, UserId;

            if(Guid.TryParse(ticketString, out Ticket) && Guid.TryParse(userIdString, out UserId))
            {
                return new UserTicketDto { Ticket = Ticket, UserObjId = UserId };
            }

            return new UserTicketDto();
        }

Web config

    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

    AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityModel.JwtClaimTypes.Name;

    app.Use(async (ctx, next) => { await next(); });

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "cookies"
    });

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        ClientId = OAuthConstant.Client,
        RedirectUri = "localhost/App/login/Login.mr",
        PostLogoutRedirectUri = "localhost/App/login/Login.mr",
        Authority = "localhost/Oauth2server/securetoken",
        SignInAsAuthenticationType = "Cookies",
        ResponseType = "token code id_token",
        Scope = "OpenId App offline_access AppAccess",
        ClientSecret = "secret",
        UseTokenLifetime = false,
        Notifications = new OpenIdConnectAuthenticationNotifications()
        {
            AuthorizationCodeReceived = IdentityServerClient.HandleOther,
            SecurityTokenReceived = IdentityServerClient.HandleOther,
            MessageReceived = IdentityServerClient.HandleOther,
            AuthenticationFailed = IdentityServerClient.HandleOther,
            RedirectToIdentityProvider = IdentityServerClient.HandleRedirectToIdentityProvider,
            SecurityTokenValidated = IdentityServerClient.HandleSecurityTokenValidated
        }
    });

Logs

2016-06-15 12:04:51.943 -05:00 [Information] Login page submitted
2016-06-15 12:04:55.320 -05:00 [Information] Login credentials successfully validated by user service
2016-06-15 12:04:55.332 -05:00 [Information] Calling PostAuthenticateAsync on the user service
2016-06-15 12:04:55.338 -05:00 [Information] issuing primary signin cookie
2016-06-15 12:04:55.344 -05:00 [Information] redirecting to: http://localhost/OAuth2Server/securetoken/connect/authorize?client_id=apphybrid&redirect_uri=http:%2F%2Flocalhost%2Fapp%2FLogin%2FLogin.mr&response_mode=form_post&response_type=code id_token token&scope=App openid offline_access AppAccess&state=OpenIdConnect.AuthenticationProperties%3DebxFcJnjMiMq2m1gPqBsYlrBWdLct2kaJSYn-s0nxImnff-37i4t8Wa3wAJewJGFe9msgeeqJDKtR1gwwfA0e8Pdd6RNAi6YPo_CqT4l5zV8ifohYQVN9TrWfLXITXuKId9IW2cCeRQL6d8uWfkzSANqAGSbSGJYZ5pgOLULQresbAiJ7N77FgBmgrVtX4hDQuwGGL5vZFCb_C5tjl8_ezH12w8zQfifKuLwjaDmOSGYyo2AqpowQXXeSSSDgKBF&nonce=636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2ZjMtODdhYmIxYTM5Mjg5
2016-06-15 12:04:55.368 -05:00 [Debug] Incoming request: /securetoken/connect/authorize
2016-06-15 12:04:55.381 -05:00 [Information] Start authorize request
2016-06-15 12:04:55.381 -05:00 [Information] Start authorize request protocol validation
2016-06-15 12:04:55.381 -05:00 [Information] "Authorize request validation success"
 "{
  "ClientId": "apphybrid",
  "ClientName": "app Hybrid Flow",
  "RedirectUri": "http://localhost/app/Login/Login.mr",
  "AllowedRedirectUris": [
    "http://localhost/app/Login/Login.mr"
  ],
  "SubjectId": "783bf872-b864-4042-853d-04fbcb7a505a",
  "ResponseType": "code id_token token",
  "ResponseMode": "form_post",
  "Flow": "Hybrid",
  "RequestedScopes": "app openid offline_access appAccess",
  "State": "OpenIdConnect.AuthenticationProperties=ebxFcJnjMiMq2m1gPqBsYlrBWdLct2kaJSYn-s0nxImnff-37i4t8Wa3wAJewJGFe9msgeeqJDKtR1gwwfA0e8Pdd6RNAi6YPo_CqT4l5zV8ifohYQVN9TrWfLXITXuKId9IW2cCeRQL6d8uWfkzSANqAGSbSGJYZ5pgOLULQresbAiJ7N77FgBmgrVtX4hDQuwGGL5vZFCb_C5tjl8_ezH12w8zQfifKuLwjaDmOSGYyo2AqpowQXXeSSSDgKBF",
  "Nonce": "636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2ZjMtODdhYmIxYTM5Mjg5",
  "SessionId": "e79cd97a339b4513b45038e7755c1b88",
  "Raw": {
    "client_id": "apphybrid",
    "redirect_uri": "http://localhost/app/Login/Login.mr",
    "response_mode": "form_post",
    "response_type": "code id_token token",
    "scope": "app openid offline_access appAccess",
    "state": "OpenIdConnect.AuthenticationProperties=ebxFcJnjMiMq2m1gPqBsYlrBWdLct2kaJSYn-s0nxImnff-37i4t8Wa3wAJewJGFe9msgeeqJDKtR1gwwfA0e8Pdd6RNAi6YPo_CqT4l5zV8ifohYQVN9TrWfLXITXuKId9IW2cCeRQL6d8uWfkzSANqAGSbSGJYZ5pgOLULQresbAiJ7N77FgBmgrVtX4hDQuwGGL5vZFCb_C5tjl8_ezH12w8zQfifKuLwjaDmOSGYyo2AqpowQXXeSSSDgKBF",
    "nonce": "636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2ZjMtODdhYmIxYTM5Mjg5"
  }
}"
2016-06-15 12:04:55.399 -05:00 [Information] Creating Hybrid Flow response.
2016-06-15 12:04:55.412 -05:00 [Information] Creating Implicit Flow response.
2016-06-15 12:04:55.416 -05:00 [Debug] Creating access token
2016-06-15 12:04:55.424 -05:00 [Debug] Getting ProfileDataAsync
2016-06-15 12:04:55.436 -05:00 [Debug] The claims in the context...
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams sub 783bf872-b864-4042-853d-04fbcb7a505a
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams name dev.guser
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams amr password
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams idp IDSRV
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams auth_time 1466010295
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams ticket fc05cd84-7756-4ec5-ac3c-53ac6d4d5e2a
2016-06-15 12:04:55.975 -05:00 [Debug] The requseted claims...
2016-06-15 12:04:55.976 -05:00 [Debug] Requested Claims Is Null
2016-06-15 12:04:55.976 -05:00 [Debug] Finished ProfileDataAsync
2016-06-15 12:04:55.982 -05:00 [Debug] Creating JWT access token
2016-06-15 12:04:56.049 -05:00 [Debug] Creating identity token
2016-06-15 12:04:56.054 -05:00 [Information] Getting claims for identity token for subject: 783bf872-b864-4042-853d-04fbcb7a505a
2016-06-15 12:04:56.054 -05:00 [Debug] Getting ProfileDataAsync
2016-06-15 12:04:56.066 -05:00 [Debug] The claims in the context...
2016-06-15 12:04:56.066 -05:00 [Debug] Cliams sub 783bf872-b864-4042-853d-04fbcb7a505a
2016-06-15 12:04:56.066 -05:00 [Debug] Cliams name dev.guser
2016-06-15 12:04:56.066 -05:00 [Debug] Cliams amr password
2016-06-15 12:04:56.066 -05:00 [Debug] Cliams idp IDSRV
2016-06-15 12:04:56.066 -05:00 [Debug] Cliams auth_time 1466010295
2016-06-15 12:04:56.066 -05:00 [Debug] Cliams ticket fc05cd84-7756-4ec5-ac3c-53ac6d4d5e2a
2016-06-15 12:04:56.338 -05:00 [Debug] The requseted claims...
2016-06-15 12:04:56.338 -05:00 [Debug] Cliams sub
2016-06-15 12:04:56.338 -05:00 [Debug] Finished ProfileDataAsync
2016-06-15 12:04:56.338 -05:00 [Debug] Creating JWT identity token
2016-06-15 12:04:56.344 -05:00 [Debug] Adding client "apphybrid" to client list cookie for subject "783bf872-b864-4042-853d-04fbcb7a505a"
2016-06-15 12:04:56.349 -05:00 [Information] End authorize request
2016-06-15 12:04:56.352 -05:00 [Information] Posting to http://localhost/app/Login/Login.mr
2016-06-15 12:04:56.352 -05:00 [Debug] Using AssetManager to render authorization response HTML
2016-06-15 12:04:56.388 -05:00 [Debug] Incoming request: /securetoken/assets/app.FormPostResponse.js

//Web 
2016-06-15 12:04:56,422 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Triggered MessageReceivedNotification`2 notification
2016-06-15 12:04:56,426 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Triggered SecurityTokenReceivedNotification`2 notification
2016-06-15 12:04:56,487 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Triggered SecurityTokenValidated notification
2016-06-15 12:04:56,487 [16] DEBUG app.Web.IdentityServer.IdentityServerClient The Claims in the identity
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: iss http://localhost/OAuth2Server/securetoken
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: aud apphybrid
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: exp 1466010416
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: nbf 1466010296
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: nonce 636016067018002117.MWY4MGVjOWItYTFjYS00MTVlLTg4MDYtMjYxYjkwMWEzNzU4ZWViNzEyNTQtMjE0Mi00MjYzLTk2ZjMtODdhYmIxYTM5Mjg5
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: iat 1466010296
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: at_hash 6pIu3P1cEeTQJMcK8Gcnhw
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: c_hash VsSw9HC0xyodlSkSCZefLw
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: sid e79cd97a339b4513b45038e7755c1b88
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: sub 783bf872-b864-4042-853d-04fbcb7a505a
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: auth_time 1466010295
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: idp IDSRV
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Claims: amr password
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient The access token: [Omitted]
2016-06-15 12:04:56,488 [16] DEBUG app.Web.IdentityServer.IdentityServerClient The id token: [Omitted]
2016-06-15 12:04:56,491 [16] DEBUG app.Web.IdentityServer.IdentityServerClient Triggered AuthenticationFailedNotification`2 notification
//Web

//Logs

The log output in question...

2016-06-15 12:04:55.412 -05:00 [Information] Creating Implicit Flow response.
2016-06-15 12:04:55.416 -05:00 [Debug] Creating access token
2016-06-15 12:04:55.424 -05:00 [Debug] Getting ProfileDataAsync
2016-06-15 12:04:55.436 -05:00 [Debug] The claims in the context...
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams sub 783bf872-b864-4042-853d-04fbcb7a505a
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams name dev.guser
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams amr password
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams idp IDSRV
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams auth_time 1466010295
2016-06-15 12:04:55.437 -05:00 [Debug] Cliams ticket fc05cd84-7756-4ec5-ac3c-53ac6d4d5e2a    <- Has the claim I want
2016-06-15 12:04:55.975 -05:00 [Debug] The requseted claims...
2016-06-15 12:04:55.976 -05:00 [Debug] Requested Claims Is Null    <- but this needs to indicate that we want that claim...
2016-06-15 12:04:55.976 -05:00 [Debug] Finished ProfileDataAsync

解决方案

Update 2: Ok now that I look closer, you have IncludeAllClaimsForUser = true. In the GetProfileData there's a comparable flag on the context. I suspect that's why you have no claims in the collection.

Update 1: Claims that you want to go into tokens should be added in GetProfile not in the AuthenticateResult in the AuthentivcateLocal method.

Original: Change the type of scope from Identity to Resource. This affects which tokens the claims go into.

这篇关于如何将声明包含在从授权端点检索的访问令牌中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆