Esempio n. 1
0
        public override Task GetProfileDataAsync(IdentityServer3.Core.Models.ProfileDataRequestContext context)
        {
            // find the user
            var subjectId = context.Subject.GetSubjectId();
            var user      = _userManager.Users.FirstOrDefault(u => u.Id == subjectId);

            // add subject as claim
            var claims = new List <Claim>
            {
                new Claim(IdentityServer3.Core.Constants.ClaimTypes.Subject, user.Id),
            };

            // add the other UserClaims
            //claims.AddRange(user.UserClaims.Select<UserClaim, Claim>(uc => new Claim(uc.ClaimType, uc.ClaimValue)));
            claims.AddRange(user.Claims.Select(uc => new Claim(uc.ClaimType, uc.ClaimValue)));

            // only return the requested claims
            if (!context.AllClaimsRequested)
            {
                claims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
            }

            // set the issued claims - these are the ones that were requested, if available
            context.IssuedClaims = claims;

            return(Task.FromResult(0));
        }
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var profileRequest = Mapper.Map<ProfileDataRequestContext, ProfileDataRequest>(context);
            var result = await domainService.GetProfileDataAsync(profileRequest);

            context.IssuedClaims = result;
        }
Esempio n. 3
0
        public override Task GetProfileDataAsync(IdentityServer3.Core.Models.ProfileDataRequestContext context)
        {
            using (var userRepository = new UserRepository())
            {
                // find the user
                var user = userRepository.GetUser(context.Subject.GetSubjectId());

                // add subject as claim
                var claims = new List <Claim>
                {
                    new Claim(Constants.ClaimTypes.Subject, user.Subject),
                };

                // add the other UserClaims
                claims.AddRange(user.UserClaims.Select <UserClaim, Claim>(
                                    uc => new Claim(uc.ClaimType, uc.ClaimValue)));

                // only return the requested claims
                if (!context.AllClaimsRequested)
                {
                    claims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
                }

                // set the issued claims - these are the ones that were requested, if available
                context.IssuedClaims = claims;

                return(Task.FromResult(0));
            }
        }
        public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var userName = context.Subject.Identity.Name;

            using (var client = new HttpClient { BaseAddress = new Uri(this.usersApiUri) })
            {
                context.IssuedClaims = await GetClaimsAsync(client, userName, context.RequestedClaimTypes ?? Enumerable.Empty<string>());
            }
        }
        public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var username = GetName(context.Subject);

            using (var client = await CreateClientAsync())
            {
                context.IssuedClaims = await GetClaimsAsync(client, username, context.RequestedClaimTypes ?? Enumerable.Empty<string>());
            }
        }
        public override Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            // issue the claims for the user
            var user = Users.SingleOrDefault(x => x.Subject == context.Subject.GetSubjectId());
            if (user != null)
            {
                context.IssuedClaims = user.Claims.Where(x => context.RequestedClaimTypes.Contains(x.Type));
            }

            return Task.FromResult(0);
        }
        public override Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            List<Claim> _claims = new List<Claim>();

            Claim _subject = context.Subject.Claims.FirstOrDefault();

            if (_subject != null)
            {
                _claims = this.BuildClaimsForSubject(_subject.Value);
            }

            context.IssuedClaims = _claims.AsEnumerable();

            return Task.FromResult(0);
        }
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            await this.innerUserService.GetProfileDataAsync(context);
            if (context.IssuedClaims == null)
            {
                return;
            }

            var userClientClaims = this.claimsService.GetUserClaimsForClient(
                context.Client?.ClientId,
                context.Subject?.Identity?.Name);

            var finalClaims = context.IssuedClaims.Union(userClientClaims);
            context.IssuedClaims = finalClaims;
        }
        public async Task<Dictionary<string, object>> ProcessAsync(string subject, IEnumerable<string> scopes, Client client)
        {
            Logger.Info("Creating userinfo response");
            var profileData = new Dictionary<string, object>();
            
            var requestedClaimTypes = await GetRequestedClaimTypesAsync(scopes);
            var principal = Principal.Create("UserInfo", new Claim("sub", subject));

            IEnumerable<Claim> profileClaims;
            if (requestedClaimTypes.IncludeAllClaims)
            {
                Logger.InfoFormat("Requested claim types: all");

                var context = new ProfileDataRequestContext(
                    principal, 
                    client, 
                    Constants.ProfileDataCallers.UserInfoEndpoint);

                await _users.GetProfileDataAsync(context);
                profileClaims = context.IssuedClaims;
            }
            else
            {
                Logger.InfoFormat("Requested claim types: {0}", requestedClaimTypes.ClaimTypes.ToSpaceSeparatedString());

                var context = new ProfileDataRequestContext(
                    principal,
                    client,
                    Constants.ProfileDataCallers.UserInfoEndpoint,
                    requestedClaimTypes.ClaimTypes);

                await _users.GetProfileDataAsync(context);
                profileClaims = context.IssuedClaims;
            }
            
            if (profileClaims != null)
            {
                profileData = profileClaims.ToClaimsDictionary();
                Logger.InfoFormat("Profile service returned to the following claim types: {0}", profileClaims.Select(c => c.Type).ToSpaceSeparatedString());
            }
            else
            {
                Logger.InfoFormat("Profile service returned no claims (null)");
            }

            return profileData;
        }
 public async Task GetProfileDataAsync(ProfileDataRequestContext context)
 {
     foreach (var service in this.services)
     {
         try
         {
             await service.GetProfileDataAsync(context);
             if (context.IssuedClaims.Any())
             {
                 return;
             }
         }
         catch
         {
             // TODO: log
         }
     }
 }
Esempio n. 11
0
        public override async Task<IEnumerable<Claim>> GetAccessTokenClaimsAsync(
           ClaimsPrincipal subject, Client client, 
           IEnumerable<Scope> scopes, ValidatedRequest request)
        {

            var claimsTask = base.GetAccessTokenClaimsAsync(subject, client, scopes, request);
            var data = new ProfileDataRequestContext(subject, client, null, new string[] { Constants.ClaimTypes.Role });
            var roleClaimsTask =  _users.GetProfileDataAsync(data); 


            var claims = await Task.WhenAll(claimsTask);
            List<IEnumerable<Claim>> lst = new List<IEnumerable<Claim>>();
            lst.AddRange(claims);

            await Task.WhenAll(roleClaimsTask);
            lst.Add(data.IssuedClaims);

            var outputClaims = lst.Where(result => result != null)
                .SelectMany(claimList => claimList).ToList();

            return outputClaims;
        }
        private async Task<ClaimsIdentity> CreateSubjectAsync(SignInValidationResult validationResult)
        {
            var profileClaims = new List<Claim>();
            var mappedClaims = new List<Claim>();

            // get all claims from user service
            if (validationResult.RelyingParty.IncludeAllClaimsForUser)
            {
                var ctx = new ProfileDataRequestContext
                {
                    Subject = validationResult.Subject,
                    AllClaimsRequested = true
                };
                await _users.GetProfileDataAsync(ctx);
                
                profileClaims = ctx.IssuedClaims.ToList();
            }
            else
            {
                // get only claims that are explicitly mapped (if any)
                var claimTypes = validationResult.RelyingParty.ClaimMappings.Keys;

                if (claimTypes.Any())
                {
                    var ctx = new ProfileDataRequestContext
                    {
                        Subject = validationResult.Subject,
                        RequestedClaimTypes = claimTypes
                    };
                    await _users.GetProfileDataAsync(ctx);

                    profileClaims = ctx.IssuedClaims.ToList();
                }
            }
            
            foreach (var claim in profileClaims)
            {
                string mappedType;

                // if an explicit mapping exists, use it
                if (validationResult.RelyingParty.ClaimMappings.TryGetValue(claim.Type, out mappedType))
                {
                    // if output claim is a SAML name ID - check is any name ID format is configured
                    if (mappedType == ClaimTypes.NameIdentifier)
                    {
                        var nameId = new Claim(ClaimTypes.NameIdentifier, claim.Value);
                        if (!string.IsNullOrEmpty(validationResult.RelyingParty.SamlNameIdentifierFormat))
                        {
                            nameId.Properties[ClaimProperties.SamlNameIdentifierFormat] = validationResult.RelyingParty.SamlNameIdentifierFormat;
                        }

                        mappedClaims.Add(nameId);
                    }
                    else
                    {
                        mappedClaims.Add(new Claim(mappedType, claim.Value));
                    }
                }
                else
                {
                    // otherwise pass-through the claims if flag is set
                    if (validationResult.RelyingParty.IncludeAllClaimsForUser)
                    {
                        string newType = claim.Type;

                        // if prefix is configured, prefix the claim type
                        if (!string.IsNullOrWhiteSpace(validationResult.RelyingParty.DefaultClaimTypeMappingPrefix))
                        {
                            newType = validationResult.RelyingParty.DefaultClaimTypeMappingPrefix + newType;
                        }

                        mappedClaims.Add(new Claim(newType, claim.Value));
                    }
                }
            }

            if (validationResult.Subject.GetAuthenticationMethod() == Constants.AuthenticationMethods.Password)
            {
                mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password));
                mappedClaims.Add(AuthenticationInstantClaim.Now);
            }
            
            return new ClaimsIdentity(mappedClaims, "idsrv");
        }
		/// <summary>
		/// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint)
		/// </summary>
		/// <param name="context">The context.</param>
		/// <returns></returns>
		public override Task GetProfileDataAsync(ProfileDataRequestContext context)
		{
			var query =
				from u in _users
				where u.Subject == context.Subject.GetSubjectId()
				select u;
			var user = query.Single();

			var claims = new List<Claim>{
				new Claim(Constants.ClaimTypes.Subject, user.Subject),
				new Claim(Constants.ClaimTypes.ExternalProviderUserId, user.ProviderId)
			};

			claims.AddRange(user.Claims);

			if (!context.AllClaimsRequested)
			{
				claims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
			}

			context.IssuedClaims = claims;

			return Task.FromResult(0);
		}
Esempio n. 14
0
 public async Task GetProfileDataAsync(ProfileDataRequestContext context)
 {
     await this.inMemoryUserService.GetProfileDataAsync(context);
 }
Esempio n. 15
0
        public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var user = await _userRepository
                .GetUserAsync(context.Subject.GetSubjectId());

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

                .Union(
                    user.UserClaims.Select(c => new Claim(c.ClaimType, c.ClaimValue)))

                .Where(c => ClaimIsRequestedOnly(context, c));

            context.IssuedClaims = claims;
        }
Esempio n. 16
0
 public Task GetProfileDataAsync(ProfileDataRequestContext context)
 {
     return Task.FromResult(0);
 }
 /// <summary>
 /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint)
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public async Task GetProfileDataAsync(ProfileDataRequestContext context)
 {
     var key = GetKey(context.Subject, context.RequestedClaimTypes);
     context.IssuedClaims = await cache.GetAsync(key, async () =>
     {
         await inner.GetProfileDataAsync(context);
         return context.IssuedClaims;
     });
 }
Esempio n. 18
0
 private static bool ClaimIsRequestedOnly(ProfileDataRequestContext context, Claim claim)
 {
     return !context.AllClaimsRequested && context.RequestedClaimTypes.Contains(claim.Type);
 }
 public override Task GetProfileDataAsync(ProfileDataRequestContext context)
 {
     var subject = context.Subject;
     //TODO Use graph client with subject as objectid to query for profile info.
     return base.GetProfileDataAsync(context);
 }
Esempio n. 20
0
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            if (context.Subject == null)
                throw new ArgumentNullException("Subject");

            var userId = Guid.Parse(context.Subject.GetSubjectId());
            var user = await this.userManager.FindByIdAsync(userId);
            if (user == null)
                throw new ArgumentException("Invalid subject identifier");

            var claims = await this.GetClaimsFromAccountAsync(user);
            if (context.RequestedClaimTypes != null && context.RequestedClaimTypes.Any())
                claims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type));

            context.IssuedClaims = claims;
        }
        /// <summary>
        /// Returns claims for an identity token.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="client">The client.</param>
        /// <param name="scopes">The requested scopes.</param>
        /// <param name="request">The raw request.</param>
        /// <returns>
        /// Claims for the access token
        /// </returns>
        public virtual async Task<IEnumerable<Claim>> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, ValidatedRequest request)
        {
            // add client_id
            var outputClaims = new List<Claim>
            {
                new Claim(Constants.ClaimTypes.ClientId, client.ClientId),
            };

            // check for client claims
            if (client.Claims != null && client.Claims.Any())
            {
                if (subject == null || client.AlwaysSendClientClaims)
                {
                    foreach (var claim in client.Claims)
                    {
                        var claimType = claim.Type;

                        if (client.PrefixClientClaims)
                        {
                            claimType = "client_" + claimType;
                        }

                        outputClaims.Add(new Claim(claimType, claim.Value, claim.ValueType));
                    }
                }
            }

            // add scopes
            foreach (var scope in scopes)
            {
                outputClaims.Add(new Claim(Constants.ClaimTypes.Scope, scope.Name));
            }

            // a user is involved
            if (subject != null)
            {
                outputClaims.AddRange(GetStandardSubjectClaims(subject));
                outputClaims.AddRange(GetOptionalClaims(subject));

                // if a include all claims rule exists, call the user service without a claims filter
                if (scopes.IncludesAllClaimsForUserRule(ScopeType.Resource))
                {
                    var context = new ProfileDataRequestContext(
                    subject,
                    client,
                    Constants.ProfileDataCallers.ClaimsProviderAccessToken);

                    await _users.GetProfileDataAsync(context);

                    var claims = FilterProtocolClaims(context.IssuedClaims);
                    if (claims != null)
                    {
                        outputClaims.AddRange(claims);
                    }

                    return outputClaims;
                }


                // fetch all resource claims that need to go into the id token
                var additionalClaims = new List<string>();
                foreach (var scope in scopes)
                {
                    if (scope.Type == ScopeType.Resource)
                    {
                        if (scope.Claims != null)
                        {
                            foreach (var scopeClaim in scope.Claims)
                            {
                                additionalClaims.Add(scopeClaim.Name);
                            }
                        }
                    }
                }

                if (additionalClaims.Count > 0)
                {
                    var context = new ProfileDataRequestContext(
                    subject,
                    client,
                    Constants.ProfileDataCallers.ClaimsProviderAccessToken,
                    additionalClaims.Distinct());

                    await _users.GetProfileDataAsync(context);

                    var claims = FilterProtocolClaims(context.IssuedClaims);
                    if (claims != null)
                    {
                        outputClaims.AddRange(claims);
                    }
                }
            }

            return outputClaims;
        }
        public override Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var currentUser = dbContext.UserProfiles.FirstOrDefault(x => x.Id.ToString() == context.Subject.GetSubjectId());

            var claims = new List<Claim>
            {
                new Claim("sub", currentUser.Id.ToString())
            };

            // Add other claims
            claims.Add(new Claim(ClaimTypes.Email, currentUser.EmailAddress));

            if(!context.AllClaimsRequested)
            {
                claims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
            }

            context.IssuedClaims = claims;
            return Task.FromResult(0);
        }
        private async Task<ClaimsIdentity> CreateSubjectAsync(SignInValidationResult validationResult)
        {
            var profileClaims = new List<Claim>();
            var mappedClaims = new List<Claim>();

            // get all claims from user service
            if (validationResult.RelyingParty.IncludeAllClaimsForUser)
            {
                var ctx = new ProfileDataRequestContext
                {
                    Subject = validationResult.Subject,
                    AllClaimsRequested = true
                };
                await _users.GetProfileDataAsync(ctx);
                
                profileClaims = ctx.IssuedClaims.ToList();
            }
            else
            {
                // get only claims that are explicitly mapped (if any)
                var claimTypes = validationResult.RelyingParty.ClaimMappings.Keys;

                if (claimTypes.Any())
                {
                    var ctx = new ProfileDataRequestContext
                    {
                        Subject = validationResult.Subject,
                        RequestedClaimTypes = claimTypes
                    };
                    await _users.GetProfileDataAsync(ctx);

                    profileClaims = ctx.IssuedClaims.ToList();
                }
            }
            
            foreach (var claim in profileClaims)
            {
                string mappedType;

                // if an explicit mapping exists, use it
                if (validationResult.RelyingParty.ClaimMappings.TryGetValue(claim.Type, out mappedType))
                {
                    // if output claim is a SAML name ID - check is any name ID format is configured
                    if (mappedType == ClaimTypes.NameIdentifier)
                    {
                        var nameId = new Claim(ClaimTypes.NameIdentifier, claim.Value);
                        if (!string.IsNullOrEmpty(validationResult.RelyingParty.SamlNameIdentifierFormat))
                        {
                            nameId.Properties[ClaimProperties.SamlNameIdentifierFormat] = validationResult.RelyingParty.SamlNameIdentifierFormat;
                        }

                        mappedClaims.Add(nameId);
                    }
                    else
                    {
                        mappedClaims.Add(new Claim(mappedType, claim.Value));
                    }
                }
                else
                {
                    // otherwise pass-through the claims if flag is set
                    if (validationResult.RelyingParty.IncludeAllClaimsForUser)
                    {
                        string newType = claim.Type;

                        // if prefix is configured, prefix the claim type
                        if (!string.IsNullOrWhiteSpace(validationResult.RelyingParty.DefaultClaimTypeMappingPrefix))
                        {
                            newType = validationResult.RelyingParty.DefaultClaimTypeMappingPrefix + newType;
                        }

                        mappedClaims.Add(new Claim(newType, claim.Value));
                    }
                }
            }

            // The AuthnStatement statement generated from the following 2
            // claims is manditory for some service providers (i.e. Shibboleth-Sp). 
            // The value of the AuthenticationMethod claim must be one of the constants in
            // System.IdentityModel.Tokens.AuthenticationMethods.
            // Password is the only one that can be directly matched, everything
            // else defaults to Unspecified.
            if (validationResult.Subject.GetAuthenticationMethod() == Constants.AuthenticationMethods.Password)
            {
                mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password));
            } else {
                mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Unspecified));
            }
            mappedClaims.Add(AuthenticationInstantClaim.Now);

            var finalClaims = await _customClaimsService.TransformClaimsAsync(validationResult, mappedClaims);

            return new ClaimsIdentity(finalClaims, "idsrv");
        }
 public Task GetProfileDataAsync(ProfileDataRequestContext context)
 {
     return inner.GetProfileDataAsync(context);
 }
Esempio n. 25
0
        /// <summary>
        /// Get Profile of User after authentication
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            try
            {
                using (var user = GetUser(context.Subject.Identity.Name))
                {
                    if (user != null)
                    {
                        var identity = new ClaimsIdentity();
                        var lstClains = GetDisplayNameForAccountAsync(user);
                        identity.AddClaims(lstClains);

                        context.IssuedClaims = identity.Claims;
                    }
                }
                return Task.FromResult(0);
            }
            catch
            {
                return Task.FromResult(0);
            }
        }
        /// <summary>
        /// Returns claims for an identity token
        /// </summary>
        /// <param name="subject">The subject</param>
        /// <param name="client">The client</param>
        /// <param name="scopes">The requested scopes</param>
        /// <param name="includeAllIdentityClaims">Specifies if all claims should be included in the token, or if the userinfo endpoint can be used to retrieve them</param>
        /// <param name="request">The raw request</param>
        /// <returns>
        /// Claims for the identity token
        /// </returns>
        public virtual async Task<IEnumerable<Claim>> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, bool includeAllIdentityClaims, ValidatedRequest request)
        {
            Logger.Info("Getting claims for identity token for subject: " + subject.GetSubjectId());

            var outputClaims = new List<Claim>(GetStandardSubjectClaims(subject));
            outputClaims.AddRange(GetOptionalClaims(subject));
            
            var additionalClaims = new List<string>();

            // if a include all claims rule exists, call the user service without a claims filter
            if (scopes.IncludesAllClaimsForUserRule(ScopeType.Identity))
            {
                Logger.Info("All claims rule found - emitting all claims for user.");

                var context = new ProfileDataRequestContext(
                    subject,
                    client,
                    Constants.ProfileDataCallers.ClaimsProviderIdentityToken);

                await _users.GetProfileDataAsync(context);
                
                var claims = FilterProtocolClaims(context.IssuedClaims);
                if (claims != null)
                {
                    outputClaims.AddRange(claims);
                }

                return outputClaims;
            }

            // fetch all identity claims that need to go into the id token
            foreach (var scope in scopes)
            {
                if (scope.Type == ScopeType.Identity)
                {
                    foreach (var scopeClaim in scope.Claims)
                    {
                        if (includeAllIdentityClaims || scopeClaim.AlwaysIncludeInIdToken)
                        {
                            additionalClaims.Add(scopeClaim.Name);
                        }
                    }
                }
            }

            if (additionalClaims.Count > 0)
            {
                var context = new ProfileDataRequestContext(
                    subject,
                    client,
                    Constants.ProfileDataCallers.ClaimsProviderIdentityToken,
                    additionalClaims);
                
                await _users.GetProfileDataAsync(context);

                var claims = FilterProtocolClaims(context.IssuedClaims);
                if (claims != null)
                {
                    outputClaims.AddRange(claims);
                }
            }

            return outputClaims;
        }
        /// <summary>
        /// This method is called whenever claims about the user are requested (e.g. during token
        /// creation or via the user info endpoint)
        /// </summary>
        /// <param name="context">The request context.</param>
        /// <returns>A "null" result</returns>
        public Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            context.IssuedClaims = new List<Claim>
            {
                _databaseClaim
            };

            return Task.FromResult(0);
        }