当前位置: 首页>>代码示例>>C#>>正文


C# ClaimsIdentity.GetUserName方法代码示例

本文整理汇总了C#中System.Security.Claims.ClaimsIdentity.GetUserName方法的典型用法代码示例。如果您正苦于以下问题:C# ClaimsIdentity.GetUserName方法的具体用法?C# ClaimsIdentity.GetUserName怎么用?C# ClaimsIdentity.GetUserName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Claims.ClaimsIdentity的用法示例。


在下文中一共展示了ClaimsIdentity.GetUserName方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetUserInfo

        public async Task<GetUserInfoResponse> GetUserInfo(ClaimsIdentity claimsIdentity)
        {
            bool isAzureActiveDirectoryUser = false;
            var hasIssClaim = claimsIdentity.FindFirst("iss");
            if (hasIssClaim != null)
            {
                if (hasIssClaim.Value.Contains("sts.windows.net"))
                {
                    isAzureActiveDirectoryUser = true;
                }
            }
            
            var userName = claimsIdentity.GetUserName();
            
            var userInfo = await _databaseRepository.GetUserInfo(userName);
            
            // if the user is unknown, we store it in our own database.
            if (userInfo == null && isAzureActiveDirectoryUser)
            {
                var firstName = claimsIdentity.Claims.Where(x => x.Type == System.IdentityModel.Claims.ClaimTypes.GivenName).Select(x => x.Value).FirstOrDefault();
                var lastName = claimsIdentity.Claims.Where(x => x.Type == System.IdentityModel.Claims.ClaimTypes.Surname).Select(x => x.Value).FirstOrDefault();

                var user = await _userService.Create(userName, userName, firstName, lastName);
                await _databaseRepository.AddToUserList(user.Id, user.UserName, user.FirstName, user.LastName);
                userInfo = await _databaseRepository.GetUserInfo(userName);
            }

            var roleClaims = new List<Claim>();
            foreach (var userRole in userInfo.Roles)
            {
                roleClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }

            var localClaimsIdentity = new ClaimsIdentity(
                   new List<Claim>
                   {
                    new Claim(ClaimTypes.Name, userInfo.UserName),
                    new Claim(ClaimTypes.GivenName, userInfo.Profile.FirstName),
                    new Claim(ClaimTypes.Surname, userInfo.Profile.LastName),
                    new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString())
                   });
            localClaimsIdentity.AddClaims(roleClaims);

            var token = localClaimsIdentity.GenerateToken(_configurationService.LocalAuthentication.AudienceId, _configurationService.LocalAuthentication.AudienceSecret, _configurationService.LocalAuthentication.Issuer, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddDays(10));
            userInfo.UserToken = token;
            return userInfo;
        }
开发者ID:CoditEU,项目名称:lunchorder,代码行数:47,代码来源:AccountControllerService.cs

示例2: Parse

 public void Parse(ClaimsIdentity identity, ref ExternalLoginData loginData)
 {
     loginData.UserName = identity.GetUserName();
     loginData.Profile = string.Format("https://twitter.com/{0}", loginData.UserName);
 }
开发者ID:juanonsoftware,项目名称:webapi-oauth-intergration,代码行数:5,代码来源:TwitterClaimsParser.cs

示例3: ConfigureAuth

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            SSOFactory.CreateOwinContext(app);

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
            //Require => error sso
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = UGConstants.SSOClient.ClientId,
                ClientSecret = UGConstants.SSOClient.ClientSecret,
                Authority = UGConstants.SSO.AuthorityBaseUri + UGConstants.SSO.PathHostIdentityServer,
                RedirectUri = UGConstants.SSOClient.RedirectUri,
                ResponseType = "id_token token",
                Scope = "openid profile",
                PostLogoutRedirectUri = UGConstants.SSOClient.PostLogoutRedirectUri,
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(n.AuthenticationTicket.Identity.Claims,
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            UGConstants.ClaimTypes.GivenName,
                            UGConstants.ClaimTypes.Role);
                        // get userinfo data
                        var userInfoClient = new UserInfoClient(
                            new Uri(n.Options.Authority + "/connect/userinfo"),
                            n.ProtocolMessage.AccessToken);
                        var userInfo = await userInfoClient.GetAsync();
                        if (userInfo.Claims != null)
                        {
                            //userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));
                            foreach (var ui in userInfo.Claims)
                            {
                                if (nid.Claims.Where(x => x.Type == ui.Item1 && x.Value == ui.Item2).Count() < 1)
                                    nid.AddClaim(new Claim(ui.Item1, ui.Item2));
                            }
                        }
                        string userName = nid.GetUserName();
                        if (string.IsNullOrWhiteSpace(userName))
                            throw new ArgumentNullException("UserName is not null or empty");
                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        // add access token for sample API
                        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                        // keep track of access token expiration
                        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                        n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);
                    },
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;

                                var signOutMessageId = n.OwinContext.Environment.GetSignOutMessageId();
                                if (signOutMessageId != null)
                                {
                                    n.OwinContext.Response.Cookies.Append("state", signOutMessageId);
                                }
                            }
                        }

                        return Task.FromResult(0);
                    }
                }
            });
        }
开发者ID:khoainv,项目名称:Framework,代码行数:84,代码来源:Startup.Manager.cs

示例4: GetLast5Orders

 public async Task<IEnumerable<LastOrder>> GetLast5Orders(ClaimsIdentity claimsIdentity)
 {
     var userInfo = await _databaseRepository.GetUserInfo(claimsIdentity.GetUserName());
     return userInfo.Last5Orders;
 }
开发者ID:CoditEU,项目名称:lunchorder,代码行数:5,代码来源:AccountControllerService.cs


注:本文中的System.Security.Claims.ClaimsIdentity.GetUserName方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。