FindFirst() public method

Retrieves the first Claim that is matched by .
Each ClaimsIdentity is called. ClaimsIdentity.FindFirst.
if 'match' is null.
public FindFirst ( Predicate match ) : Claim
match Predicate The predicate that performs the matching logic.
return Claim
        /// <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));
            }
        }
Example #2
0
        /*
        * @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;
        }
Example #3
0
 //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;
 }
        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));
        }
Example #5
0
        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));
        }
Example #6
0
 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;
 }
        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;

      
     
          
    }
        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;
        }
        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;
        }
        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;
        }
Example #11
0
        //[HttpGet("getContactTemplate")]
        //public object GetContactTemplate()
        //{
        //    Contact contact = new Contact();
        //    ContactType[] contactTypes = this.db.ContactTypes.ToArray();
        //    ContactSource[] contactSources = this.db.ContactSources.ToArray();
        //    return new { contact = contact, contactType = contactTypes, contactSource = contactSources };
        //}


        private async ValueTask <ApplicationUser> GetUserAsync()
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;

            return(await _userManager.FindByIdAsync(currentUserId));
        }
        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);
        }
        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;
        }
 private static string GetClaim(ClaimsPrincipal principal, string claimType)
 {
   Claim claim = principal.FindFirst(claimType);
   if (claim != null)
     return claim.Value;
   return string.Empty;
 }
        public async Task <IEnumerable <WeatherForecast> > Get(/*, IsActiveContext isActivecontext*/)//string returnUrl = null)
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            // var user = await _userManager.GetUserAsync(User);
            var userName = await _userManager.GetUserAsync(User);// var user = await _userManager.GetUserAsync(User);

            var             currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
            ApplicationUser user          = await _userManager.FindByIdAsync(currentUserId);


            //var sub = profileDatacontext.Subject.GetSubjectId();
            //var user = await _userManager.FindByIdAsync(sub);
            //var principal = await _claimsFactory.CreateAsync(user);

            //var claims = principal.Claims.ToList();
            //claims = claims.Where(claim => profileDatacontext.RequestedClaimTypes.Contains(claim.Type)).ToList();
            //claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName));

            var rng = new Random();

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
                   .ToArray());
        }
        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;
        }
        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;
        }
        public static bool CheckAuthorization(this System.Security.Claims.ClaimsPrincipal user, Guid memberId)
        {
            if (user == null)
            {
                return(false);
            }

            if (user.FindFirst(ClaimTypes.NameIdentifier) == null)
            {
                return(false);
            }

            if (memberId != Guid.Parse(user.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(false);
            }

            return(true);
        }
        private bool HasScopeClaim(ClaimsPrincipal principal, string scope)
        {
            if (principal == null || !principal.Identity.IsAuthenticated)
            {
                return false;
            }

            var claim = principal.FindFirst(c => c.Type == "scope");
            return claim != null && !String.IsNullOrEmpty(claim.Value) &&
                    (claim.Value == scope || (claim.Value.Contains(" ") && claim.Value.Split(' ').Any(s => s == scope)));
        }
        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 tenantClaim = incomingPrincipal.FindFirst(TenantIdClaim);
                if (tenantClaim == null)
                {
                    throw new NotSupportedException("Tenant claim not available, role authentication is not supported");
                }
                Claim objectIdentifierClaim = incomingPrincipal.FindFirst(ObjectIdentifierClaim);
                if (objectIdentifierClaim == null)
                {
                    throw new NotSupportedException("Object identifier claim not available, role authentication is not supported");
                }

                string tenantId = tenantClaim.Value;
                string currentUserObjectId = objectIdentifierClaim.Value;

                // Connect to the graph service
                AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantId, _clientId, _password);
                DirectoryDataService graphService = new DirectoryDataService(tenantId, token);

                // Find the user in the graph
// ReSharper disable once ReplaceWithSingleCallToSingleOrDefault - SingleOrDefault not supported on directory service directly
                User currentUser = graphService.directoryObjects.OfType<User>().Where(it => (it.objectId == currentUserObjectId)).SingleOrDefault();
                if (currentUser == null)
                {
                    throw new SecurityException("User cannot be found in graph");
                }

                // Find the groups the user is a member of and add them as role claims
                graphService.LoadProperty(currentUser, "memberOf");
                List<Group> currentRoles = currentUser.memberOf.OfType<Group>().ToList();
                foreach (Group role in currentRoles)
                {
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role.displayName, ClaimValueTypes.String, _issuer));
                }
            }
            return base.Authenticate(resourceName, incomingPrincipal);
        }
        public override void ResponseSignIn(CookieResponseSignInContext context)
        {
            var principle = new ClaimsPrincipal(context.Identity);
            var pictureClaim = principle.FindFirst("profilePicture");
            var idClaim = principle.FindFirst(ClaimTypes.NameIdentifier);
            var nameClaim = principle.FindFirst(ClaimTypes.Name);
            var emailClaim = principle.FindFirst(ClaimTypes.Email);

            var id = idClaim == null ? Guid.NewGuid().ToString() : idClaim.Value;
            var name = nameClaim == null ? "unknown" : System.Net.WebUtility.HtmlEncode(nameClaim.Value);
            var photo = pictureClaim != null ? pictureClaim.Value :  GetPhotoUrl(emailClaim == null ? "" : emailClaim.Value);

            var rc = new RegisteredClient()
            {
                Identity = id,
                DisplayName = name,
                Photo = photo
            };

            SetState(rc, context.Response);
        }
        public static ClaimsPrincipal CreateFromPrincipal(ClaimsPrincipal principal, string authenticationType)
        {
            // we require the following claims
            var subject = principal.FindFirst(JwtClaimTypes.Subject);
            if (subject == null) throw new InvalidOperationException("sub claim is missing");

            var name = principal.FindFirst(JwtClaimTypes.Name);
            if (name == null) throw new InvalidOperationException("name claim is missing");

            var authenticationMethod = principal.FindFirst(JwtClaimTypes.AuthenticationMethod);
            if (authenticationMethod == null) throw new InvalidOperationException("amr claim is missing");

            var authenticationTime = principal.FindFirst(JwtClaimTypes.AuthenticationTime);
            if (authenticationTime == null) throw new InvalidOperationException("auth_time claim is missing");

            var idp = principal.FindFirst(JwtClaimTypes.IdentityProvider);
            if (idp == null) throw new InvalidOperationException("idp claim is missing");

            var id = new ClaimsIdentity(principal.Claims, authenticationType, JwtClaimTypes.Name, JwtClaimTypes.Role);
            return new ClaimsPrincipal(id);
        }
        private static async Task<ClaimsPrincipal> TransformClaims(ClaimsPrincipal incoming)
        {
            if (!incoming.Identity.IsAuthenticated)
            {
                return incoming;
            }

            var context = HttpContext.Current.GetOwinContext().GetAutofacLifetimeScope();

            var manager = context.Resolve<ApplicationUserManager>();

            var user = await manager.FindByIdAsync(incoming.FindFirst("sub").Value);
            var identity = await manager.CreateIdentityAsync(user, "API");

            return new ClaimsPrincipal(identity);
        }
 static string Get(ClaimsPrincipal claimsPrincipal, string type, bool isRequired = false)
 {
     Claim subject = claimsPrincipal.FindFirst(type);
     if (subject == null)
     {
         if (isRequired)
         {
             throw new Exception(string.Format("required Claim {0} not found", type));
         }
         else
         {
             return null;
         }
     }
     return subject.Value;
 }
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            var name = incomingPrincipal.Identity.Name;

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new SecurityException("No user name found");
            }

            var location = incomingPrincipal.FindFirst("http://myclaims/location").Value;

            if (string.IsNullOrWhiteSpace(location))
            {
                throw new SecurityException("No location found");
            }

            return CreateUserPrincipal(name, location);
        }
 public bool IsValidEmail(ClaimsPrincipal claimsPrincipal)
 {
     Claim emailClaim = claimsPrincipal.FindFirst(x => x.Type == ClaimTypes.Email);
     if (emailClaim == null)
     {
         _log.ErrorFormat("No mandatory parameter: {0}", ClaimTypes.Email);
         return false;
     }
     try
     {
         new MailAddress(emailClaim.Value);
         return true;
     }
     catch
     {
         _log.ErrorFormat("Wrong email format: {0}", emailClaim.Value);
         return false;
     }
 }
Example #27
0
        public static string GetUserId(ClaimsPrincipal principal)
        {
            var userId = string.Empty;

            try
            {
                userId =
                    principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            }
            catch (Exception)
            {
#if DEBUG
                userId = "auth0|56262b38fa9ddfa52a21efa6";
#else
                throw;
#endif
            }

            return userId;
        }
Example #28
0
        public loginInInfo isUserLogin()
        {
            loginInInfo loginInfo = new loginInInfo();

            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var isUserLogin = currentUser.Identity.IsAuthenticated;

            if (!isUserLogin)
            {
                loginInfo.isLogin = false;
                loginInfo.userId  = null;
            }

            if (isUserLogin)
            {
                var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
                loginInfo.isLogin = true;
                loginInfo.userId  = currentUserID;
            }

            return(loginInfo);
        }
        public async Task<AgreementRecord> GetAgreement(string agreement, string agreementVersion, ClaimsPrincipal claimsPrincipal)
        {
            CloudTableClient client = _account.CreateCloudTableClient();
            CloudTable table = client.GetTableReference(AgreementTableName);
           
            TableQuery<AgreementRecordEntity> query = new TableQuery<AgreementRecordEntity>()
                    .Where(TableQuery.CombineFilters(
                        TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal,  AgreementRecord.GetKey(claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value, agreement)),
                        TableOperators.And,
                        TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, agreementVersion)));

            TableQuerySegment<AgreementRecordEntity> segment =
                await table.ExecuteQuerySegmentedAsync(query, new TableContinuationToken());

            if (segment.Results.Count > 0)
            {
                var entity = segment.Results.First();
                return entity.ToAgreementRecord();
            }

            return null;
        }
Example #30
0
        public static async Task<String> GetJSON(ClaimsPrincipal user, String method, String jsonParams)
        {
            String result = null;

            var __token = user.FindFirst(MyClaimTypes.Token).Value;

            var url = String.Format(AppConst.Http+"://{0}/{1}?token={2}", AppConst.ServerName, method, __token);

            try
            {



                StringContent stringContent = new StringContent(jsonParams??String.Empty);
                stringContent.Headers.ContentType.MediaType = "application/json";

                using (HttpClient client = new HttpClient())
                {
                    using (HttpResponseMessage response = await client.PostAsync(url, stringContent))
                    {
                        using (HttpContent content = response.Content)
                        {
                            String __content = await content.ReadAsStringAsync();
                            response.EnsureSuccessStatusCode();                            
                            //result = JsonConvert.DeserializeObject<AccountDetailInfo>(__content);
                            result = __content;
                            
                        }
                    }
                }
            }
            catch (Exception __ex)
            {
                Debug.WriteLine(__ex);
            }

            return result;
        }
 public static string GetDetailsStamp(this ClaimsPrincipal user)
 {
     return(user?.FindFirst(BlogConstants.Claims.DetailsStamp)?.Value);
 }
Example #32
0
        public Saml2LogoutRequest CreateLogoutRequest(ClaimsPrincipal user)
        {
            if (user == null) throw new ArgumentNullException(nameof(user));
            if (spOptions.SigningServiceCertificate == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                    "Tried to issue single logout request to {0}, but no signing certificate for the SP is configured and single logout requires signing. Add a certificate to the ISPOptions.ServiceCertificates collection, or to <serviceCertificates> element if you're using web.config.",
                    EntityId.Id));
            }

            return new Saml2LogoutRequest()
            {
                DestinationUrl = SingleLogoutServiceUrl,
                Issuer = spOptions.EntityId,
                NameId = user.FindFirst(AuthServicesClaimTypes.LogoutNameIdentifier)
                            .ToSaml2NameIdentifier(),
                SessionIndex =
                    user.FindFirst(AuthServicesClaimTypes.SessionIndex).Value,
                SigningCertificate = spOptions.SigningServiceCertificate,
            };
        }
        protected virtual void SetPrincipal(HttpRequestMessage request, ClaimsPrincipal principal)
        {
            if (principal.Identity.IsAuthenticated)
            {
                string name = "unknown";

                if (!string.IsNullOrWhiteSpace(principal.Identity.Name))
                {
                    name = principal.Identity.Name;
                }
                else if (!string.IsNullOrWhiteSpace(principal.FindFirst(ClaimTypes.NameIdentifier).Value))
                {
                    name = principal.Identity.Name;
                }
                else if (!string.IsNullOrWhiteSpace(principal.FindFirst("sub").Value))
                {
                    name = principal.Identity.Name;
                }
                else if (principal.Claims.First() != null)
                {
                    name = principal.Claims.First().Value;
                }

                Tracing.Verbose("Principal set for: " + name);
            }
            else
            {
                Tracing.Verbose("Setting anonymous principal.");
            }

            request.GetRequestContext().Principal = principal;

            if (_authN.Configuration.SetPrincipalOnRequestInstance)
            {
                request.Properties[PrincipalKey] = principal;
            }
        }
Example #34
0
 public static string GetUsername(this System.Security.Claims.ClaimsPrincipal user)
 {
     return(user.FindFirst(ClaimTypes.Name)?.Value);
 }
Example #35
0
        public static string?GetIdentity(this ClaimsPrincipal principal)
        {
            var identity = principal?.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");

            return(identity?.Value);
        }
Example #36
0
 /// <summary>
 /// Get user name
 /// </summary>
 /// <param name="principal"></param>
 /// <returns></returns>
 public static string GetUserName(this ClaimsPrincipal principal) =>
 principal.FindFirst(ClaimTypes.Upn) != null?
 principal.FindFirst(ClaimTypes.Upn).Value:
 principal.FindFirst(ClaimTypes.Email).Value;
        public UserInfo CreateUserInfo(ClaimsPrincipal claimsPrincipal, string profile)
        {
            Claim extUserIdClaim = claimsPrincipal.FindFirst(SupportedClaimTypes.ExtUserId);
            var email = claimsPrincipal.FindFirst(ClaimTypes.Email).Value;
            UserInfo userInfo = null;
            
            if (extUserIdClaim != null && !string.IsNullOrWhiteSpace(extUserIdClaim.Value))
            {
                var wrapper = new CommonDbWrapper();
                var userId = wrapper.GetUserId(extUserIdClaim.Value, profile);
                if (userId != null)
                {
                    _log.DebugFormat("Updating new user with extUserId: {0}", extUserIdClaim.Value);
                    userInfo = CoreContext.UserManager.GetUsers(Guid.Parse(userId));

                    while (true)
                    {
                        int count = 0;
                        var userByEmail = CoreContext.UserManager.GetUserByEmail(email);
                        if (userByEmail == Constants.LostUser || userByEmail.ID == userInfo.ID)
                        {
                            break;
                        }
                        email += count++;
                    }
                }
                if (userId == null || userInfo == Constants.LostUser)
                {
                    _log.DebugFormat("Creating new user with extUserId: {0}", extUserIdClaim.Value);
                    userInfo = new UserInfo();
                    wrapper.SaveExtUserId(extUserIdClaim.Value, userInfo.ID.ToString(), profile);
                    while (true)
                    {
                        int count = 0;
                        if (CoreContext.UserManager.GetUserByEmail(email) == Constants.LostUser)
                        {
                            break;
                        }
                        email += count++;
                    }
                }
            }
            else
            {
                userInfo = CoreContext.UserManager.GetUserByEmail(email);
                if (userInfo == Constants.LostUser)
                {
                    _log.DebugFormat("Creating new user with email: {0}", email);
                    userInfo = new UserInfo();
                }
                else
                {
                    _log.DebugFormat("Updating user with email: {0}", email);
                }
            }
            Claim givenNameClaim = claimsPrincipal.FindFirst(ClaimTypes.GivenName);
            Claim surNameClaim = claimsPrincipal.FindFirst(ClaimTypes.Surname);
            Claim mobilePhoneClaim = claimsPrincipal.FindFirst(ClaimTypes.MobilePhone);
            Claim titleClaim = claimsPrincipal.FindFirst(SupportedClaimTypes.Title);
            Claim locationClaim = claimsPrincipal.FindFirst(ClaimTypes.StreetAddress);
            Claim birthDateClaim = claimsPrincipal.FindFirst(ClaimTypes.DateOfBirth);
            Claim sexClaim = claimsPrincipal.FindFirst(SupportedClaimTypes.Sex);

            userInfo.ActivationStatus = EmployeeActivationStatus.Activated;
            userInfo.Email = email;
            userInfo.FirstName = givenNameClaim != null ? givenNameClaim.Value : string.Empty;
            userInfo.LastName = surNameClaim != null ? surNameClaim.Value : string.Empty;
            userInfo.MobilePhone = mobilePhoneClaim != null ? mobilePhoneClaim.Value : string.Empty;
            userInfo.Title = titleClaim != null ? titleClaim.Value : string.Empty;
            userInfo.Location = locationClaim != null ? locationClaim.Value : string.Empty;
            string firstName = givenNameClaim != null ? givenNameClaim.Value : string.Empty;
            string lastName = surNameClaim != null ? surNameClaim.Value : string.Empty;
            string mobilePhone = mobilePhoneClaim != null ? mobilePhoneClaim.Value : string.Empty;
            string title = titleClaim != null ? titleClaim.Value : string.Empty;
            string location = locationClaim != null ? locationClaim.Value : string.Empty;
            string birthDateString = birthDateClaim != null ? birthDateClaim.Value : null;
            string sexString = sexClaim != null ? sexClaim.Value : null;

            if (!string.IsNullOrEmpty(firstName))
            {
                if (firstName.Length > MAX_NUMBER_OF_SYMBOLS)
                {
                    firstName = firstName.Substring(0, MAX_NUMBER_OF_SYMBOLS);
                }
                userInfo.FirstName = firstName;
            }
            if (!string.IsNullOrEmpty(lastName))
            {
                if (lastName.Length > MAX_NUMBER_OF_SYMBOLS)
                {
                    lastName = lastName.Substring(0, MAX_NUMBER_OF_SYMBOLS);
                }
                userInfo.LastName = lastName;
            }
            if (!string.IsNullOrEmpty(mobilePhone))
            {
                userInfo.MobilePhone = mobilePhone;
            }
            if (!string.IsNullOrEmpty(title))
            {
                userInfo.Title = title;
            }
            if (!string.IsNullOrEmpty(location))
            {
                userInfo.Location = location;
            }
            if (!string.IsNullOrEmpty(birthDateString))
            {
                try
                {
                    userInfo.BirthDate = DateTime.Parse(birthDateString);
                }
                catch (Exception e)
                {
                    _log.ErrorFormat("Parse birthDateString error: {0}, {1}", e, birthDateString);
                }
            }

            if (!string.IsNullOrEmpty(sexString))
            {
                try
                {
                    userInfo.Sex = Convert.ToBoolean(sexString);
                }
                catch (Exception e)
                {
                    _log.ErrorFormat("Parse sexString error: {0}, {1}", e, sexString);
                }
            }

            if (!userInfo.WorkFromDate.HasValue)
            {
                userInfo.WorkFromDate = TenantUtil.DateTimeNow();
            }

            return userInfo;
        }
 public static string GetUsername(this ClaimsPrincipal user)
 {
     return(user?.FindFirst(BlogConstants.Claims.Username)?.Value);
 }
        /// <summary>
        /// Gets additional (and optional) claims from the cookie or incoming subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <returns>Additional claims</returns>
        protected virtual IEnumerable<Claim> GetOptionalClaims(ClaimsPrincipal subject)
        {
            var claims = new List<Claim>();

            var acr = subject.FindFirst(Constants.ClaimTypes.AuthenticationContextClassReference);
            if (acr.HasValue()) claims.Add(acr);

            return claims;
        }
Example #40
0
 public static int GetUserId(this System.Security.Claims.ClaimsPrincipal user)
 {
     return(int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value));
 }