博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

oidc User.Identity.Name 为空解决方法

Posted on 2018-04-24 16:26  生命如风  阅读(999)  评论(0编辑  收藏  举报
     public override Task TicketReceived(TicketReceivedContext context)
        {
var result = base.TicketReceived(context);

            var identity = context.Principal.Identity as ClaimsIdentity;
            if (identity != null)
            {
                // Add the Name ClaimType. This is required if we want User.Identity.Name to actually return something!
                if (!context.Principal.HasClaim(c => c.Type == ClaimTypes.Name) &&
                identity.HasClaim(c => c.Type == "name"))
                    identity.AddClaim(new Claim(ClaimTypes.Name, identity.FindFirst("name").Value));

                // Check if token names are stored in Properties
                if (context.Properties.Items.ContainsKey(".TokenNames"))
                {
                    // Token names a semicolon separated
                    string[] tokenNames = context.Properties.Items[".TokenNames"].Split(';');

                    // Add each token value as Claim
                    foreach (var tokenName in tokenNames)
                    {
                        // Tokens are stored in a Dictionary with the Key ".Token.<token name>"
                        string tokenValue = context.Properties.Items[$".Token.{tokenName}"];
                        identity.AddClaim(new Claim(tokenName, tokenValue));
                    }
                }
            }
           return result;
        }