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


C# ClaimsPrincipal.FindFirst方法代码示例

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


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

示例1: CreatePrincipal

        private static ClaimsPrincipal CreatePrincipal(ClaimsPrincipal principal)
        {
            string profileKey = principal.FindFirst(MyClaimTypes.ProfileKey).Value;

            List<Claim> claims = new List<Claim>();
            using (var session = Store.OpenSession())
            {
                var profile = session.Load<Profile>(profileKey);

                claims.AddRange(new[]
                {
                    // copy over claim with profile key
                    principal.FindFirst(MyClaimTypes.ProfileKey),

                    new Claim(ClaimTypes.NameIdentifier, profile.Username),

                    // add custom claims here
                    //new Claim(ClaimTypes.Email, profile.Email),
                    //new Claim(ClaimTypes.Name, profile.FirstName),
                    new Claim(ClaimTypes.GivenName, profile.Name)
                });
                claims.AddRange(profile.Roles.Select(role => new Claim(ClaimTypes.Role, role)));
            }

            return new ClaimsPrincipal(new ClaimsIdentity(claims.ToArray(), "Application",
                ClaimTypes.NameIdentifier, ClaimTypes.Role));
        }
开发者ID:tzarger,项目名称:contrib,代码行数:27,代码来源:AuthenticationManager.cs

示例2: NormalizeClaims

        /// <summary>
        /// Transforms the claims from AAD to well-known claims.
        /// </summary>
        /// <param name="principal">The current <see cref="System.Security.Claims.ClaimsPrincipal"/></param>
        private static void NormalizeClaims(ClaimsPrincipal principal)
        {
            Guard.ArgumentNotNull(principal, nameof(principal));

            var identity = principal.Identities.First();
            if (!identity.IsAuthenticated)
            {
                throw new InvalidOperationException("The supplied principal is not authenticated.");
            }

            var email = principal.FindFirst(ClaimTypes.Upn)?.Value;
            if (!string.IsNullOrWhiteSpace(email))
            {
                identity.AddClaim(new Claim(ClaimTypes.Email, email));
            }

            var name = principal.GetDisplayNameValue();
            if (!string.IsNullOrWhiteSpace(name))
            {
                // It looks like AAD does something strange here, but it's actually the JwtSecurityTokenHandler making assumptions
                // about the claims from AAD.  It takes the unique_name claim from AAD and maps it to a ClaimTypes.Name claim, which
                // is the default type for a name claim for our identity.  If we don't remove the old one, there will be two name claims,
                // so let's get rid of the first one.
                var previousNameClaim = principal.FindFirst(ClaimTypes.Name);
                if (previousNameClaim != null)
                {
                    identity.RemoveClaim(previousNameClaim);
                }
                identity.AddClaim(new Claim(identity.NameClaimType, name));
            }
        }
开发者ID:Azure-Samples,项目名称:guidance-identity-management-for-multitenant-apps,代码行数:35,代码来源:SurveyAuthenticationEvents.cs

示例3: UserSession

 //ClaimsPrincipal is where the GenericPrincipal derives from
 public UserSession(ClaimsPrincipal principal)
 {
     UserId = Guid.Parse(principal.FindFirst(ClaimTypes.Sid).Value);
     Email = principal.FindFirst(ClaimTypes.Email).Value;
     FirstName = principal.FindFirst(ClaimTypes.GivenName).Value;
     LastName = principal.FindFirst(ClaimTypes.Surname).Value;
 }
开发者ID:ethionutrition,项目名称:ethioNut,代码行数:8,代码来源:UserSession.cs

示例4: getMemberID

        /*
        * @brief Before setup the authentication provider in Azure Portal MobileApp, return passed memberID for dev and test purpose. \n
        * @param pMemberID
        * @param pClaim object
        */
        public static string getMemberID(string pMemberID, ClaimsPrincipal pClaim)
        {
            string sid;

            try
            {
                if (pClaim.FindFirst(ClaimTypes.NameIdentifier) == null)
                {
                    /// local or non-authentication provider
                    sid = pMemberID;
                }
                else
                {
                    /// authentication provider set up
                    /// return SID from claim object
                    sid = pClaim.FindFirst(ClaimTypes.NameIdentifier).Value.Replace("sid:", "");
                }
            }
            catch (Exception)
            {

                throw;
            }

            return sid;
        }
开发者ID:RumbleKAT,项目名称:CloudBread,代码行数:31,代码来源:CBAuth.cs

示例5: TransformClaims

        private Task<ClaimsPrincipal> TransformClaims(ClaimsPrincipal incoming)
        {
            if (!incoming.Identity.IsAuthenticated)
            {
                return Task.FromResult<ClaimsPrincipal>(incoming);
            }

            // parse incoming claims - create new principal with app claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "foo"),
                new Claim(ClaimTypes.Role, "bar")
            };

            var nameId = incoming.FindFirst(ClaimTypes.NameIdentifier);
            if (nameId != null)
            {
                claims.Add(nameId);
            }

            var thumbprint = incoming.FindFirst(ClaimTypes.Thumbprint);
            if (thumbprint != null)
            {
                claims.Add(thumbprint);
            }

            var id = new ClaimsIdentity("Application");
            id.AddClaims(claims);

            return Task.FromResult<ClaimsPrincipal>(new ClaimsPrincipal(id));
        }
开发者ID:RyanLiu99,项目名称:Thinktecture.IdentityModel,代码行数:31,代码来源:Startup.cs

示例6: UserSession

 public UserSession(ClaimsPrincipal principal)
 {
     UserId = int.Parse(principal.FindFirst(ClaimTypes.Sid).Value);
     SessionToken = principal.FindFirst(ClaimTypes.PrimarySid).Value;
     PayorId = int.Parse(principal.FindFirst(ClaimTypes.PrimaryGroupSid).Value);
     PayorName = principal.FindFirst(CustomClaimType.PayorName.ToString()).Value;
     Username = principal.FindFirst(ClaimTypes.Name).Value;
 }
开发者ID:Unleadedblues,项目名称:PayMaster,代码行数:8,代码来源:UserSession.cs

示例7: Authenticate

        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
         {

             if (incomingPrincipal != null &&

                   incomingPrincipal.Identity.IsAuthenticated == true)
             {

                 string tenantId = incomingPrincipal.FindFirst(TenantIdClaimType).Value;

                 // Get a token for calling the Windows Azure Active Directory Graph
                 AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, LoginUrl, tenantId));
                 ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey);
                 AuthenticationResult assertionCredential = authContext.AcquireToken(GraphUrl, credential);
                 string authHeader = assertionCredential.CreateAuthorizationHeader();
                 string requestUrl = String.Format(
                     CultureInfo.InvariantCulture,
                       GroupMemberUrl,
                     HttpUtility.UrlEncode(tenantId),
                     HttpUtility.UrlEncode(incomingPrincipal.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value));

                 HttpClient client = new HttpClient();
                 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                 request.Headers.TryAddWithoutValidation("Authorization", authHeader);

                 var taskresponse = client.SendAsync(request);

                 var wat = taskresponse.Result;

                 HttpResponseMessage response = wat;

                 var response2 = response.Content.ReadAsStringAsync();

                 string responseString = response2.Result;

                 List<ADGroup> objects = JsonConvert.DeserializeObject<dynamic>(responseString)["value"].ToObject<List<ADGroup>>();

                 var groups = from g in objects where g.objectType.Equals("Group") select g.displayName;


                 foreach (string s in groups)

                     ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(

                              new Claim(ClaimTypes.Role, s, ClaimValueTypes.String, "GRAPH"));



             }

            return incomingPrincipal;

      
     
          
    }
开发者ID:InFlowBPM,项目名称:InFlow-BPMS,代码行数:56,代码来源:GraphClaimsAuthenticationManager.cs

示例8: GetAccessTokenClaimsAsync

        public override async Task<IEnumerable<Claim>> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, ValidatedRequest request)
        {
            var claims = await base.GetAccessTokenClaimsAsync(subject, client, scopes, request);

            var newClaims = claims.ToList();
            newClaims.Add(subject.FindFirst(Constants.ClaimTypes.Name));
            newClaims.Add(subject.FindFirst(Constants.ClaimTypes.Email));
            //newClaims.Add(subject.FindFirst(Constants.ClaimTypes.PreferredUserName));

            return newClaims;
        }
开发者ID:khoainv,项目名称:Framework,代码行数:11,代码来源:CustomClaimsProvider.cs

示例9: GetStandardSubjectClaims

        protected virtual IEnumerable<Claim> GetStandardSubjectClaims(ClaimsPrincipal subject)
        {
            var claims = new List<Claim>
            {
                subject.FindFirst(Constants.ClaimTypes.Subject),
                subject.FindFirst(Constants.ClaimTypes.AuthenticationMethod),
                subject.FindFirst(Constants.ClaimTypes.AuthenticationTime),
                subject.FindFirst(Constants.ClaimTypes.IdentityProvider)
            };

            return claims;
        }
开发者ID:ErikM040566,项目名称:Thinktecture.IdentityServer.v3,代码行数:12,代码来源:DefaultClaimsProvider.cs

示例10: GetSubject

        protected override string GetSubject(ClaimsPrincipal principal)
        {
            var nameId = principal.FindFirst(ClaimTypes.NameIdentifier);
            if (nameId == null)
            {
                nameId = principal.FindFirst(ClaimTypes.Name);
                if (nameId == null)
                {
                    throw new InvalidOperationException("No nameidentifier claim");
                }
            }

            return nameId.Value;
        }
开发者ID:Excelsior-Charles,项目名称:Thinktecture.AuthorizationServer,代码行数:14,代码来源:NameIdOrNameToSubjectClaimsTransformer.cs

示例11: GetClaim

 private static string GetClaim(ClaimsPrincipal principal, string claimType)
 {
   Claim claim = principal.FindFirst(claimType);
   if (claim != null)
     return claim.Value;
   return string.Empty;
 }
开发者ID:eowemanuel,项目名称:Orchid_SkillSmart,代码行数:7,代码来源:SkillsmartUser.cs

示例12: GetOutputClaimsIdentity

        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (principal == null)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            // check github
            string ak = principal.FindFirst(Constants.CLAIM_TYPE_GITHUB_AK).Value;
            string openid = Utility.GetOpenId(ak);

            // check account
            ADAccountInfo info = AccountHelper.GetHelper().GetAccount(openid);

            if (info == null)
            {
                throw new InvalidRequestException("wrong github login or not binded, cannot login.");
            }

            var claims = new[]
            {
                new Claim(Constants.CLAIM_TYPE_PRIMARY_SID, info.primarysid),
                new Claim(System.IdentityModel.Claims.ClaimTypes.Upn, info.upnUpper),
                new Claim(System.IdentityModel.Claims.ClaimTypes.Upn, info.upnLower),
                new Claim(System.IdentityModel.Claims.ClaimTypes.Name, info.name),
            };

            var id = new ClaimsIdentity(claims);

            return id;
        }
开发者ID:msopentechcn,项目名称:dynamics-crm-social-login-sts,代码行数:31,代码来源:CustomSecurityTokenService.cs

示例13: Authenticate

        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
            {
                // Get the claims required to make further Graph API enquiries about the user
                //Claim nameIdClaim = incomingPrincipal.FindFirst(NameIdClaim);
                //if (nameIdClaim == null)
                //{
                //    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                //}
                Claim nameClaim = incomingPrincipal.FindFirst(NameClaim);
                if (nameClaim == null)
                {
                    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                }

                string userName = nameClaim.Value;
                //string currentUserObjectId = objectIdentifierClaim.Value;

                //load up the roles as RoleClaims
                TableUser user = new TableUser(userName);
                Task<IList<string>> t = _userStore.GetRolesAsync(user);
                t.RunSynchronously();
                IList<string> currentRoles = t.Result;
                foreach (string role in currentRoles)
                {
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, _issuer));
                }
            }
            return base.Authenticate(resourceName, incomingPrincipal);
        }
开发者ID:4deeptech,项目名称:AccidentalFish.AspNet.Identity.Azure,代码行数:31,代码来源:AzureTableRoleClaimsAuthenticationManager.cs

示例14: GetAccessTokenClaimsAsync

        public override async Task<IEnumerable<Claim>> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, ValidatedRequest request)
        {
            var claims = await base.GetAccessTokenClaimsAsync(subject, client, scopes, request);

            var newClaims = claims.ToList();
            newClaims.Add(subject.FindFirst("account_store"));

            return newClaims;
        }
开发者ID:mequanta,项目名称:Janitor-old,代码行数:9,代码来源:CustomClaimsProvider.cs

示例15: GetSubject

        protected override string GetSubject(ClaimsPrincipal principal)
        {
            var subject = principal.FindFirst(Constants.ClaimTypes.Subject);
            if (subject == null)
            {
                subject = principal.FindFirst(ClaimTypes.NameIdentifier);
                if (subject == null)
                {
                    subject = principal.FindFirst(ClaimTypes.Name);
                    if (subject == null)
                    {
                        throw new InvalidOperationException("No subject identifier claim");
                    }
                }
            }

            return subject.Value;
        }
开发者ID:Griimm,项目名称:Thinktecture.AuthorizationServer,代码行数:18,代码来源:SubjectClaimsTransformer.cs


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