public IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            // email address
            string email = Membership.FindUsersByName(userName)[userName].Email;
            if (!String.IsNullOrEmpty(email))
            {
                claims.Add(new Claim(ClaimTypes.Email, email));
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            if (ProfileManager.Enabled)
            {
                var profile = ProfileBase.Create(userName, true);
                if (profile != null)
                {
                    foreach (SettingsProperty prop in ProfileBase.Properties)
                    {
                        string value = profile.GetPropertyValue(prop.Name).ToString();
                        if (!String.IsNullOrWhiteSpace(value))
                        {
                            claims.Add(new Claim(ProfileClaimPrefix + prop.Name.ToLowerInvariant(), value));
                        }
                    }
                }
            }

            return claims;
        }
        public virtual IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            var nameIdClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
            if (nameIdClaim == null)
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userName));
            }

            // email address
            var membership = Membership.FindUsersByName(userName)[userName];
            if (membership != null)
            {
                string email = membership.Email;
                if (!String.IsNullOrEmpty(email))
                {
                    claims.Add(new Claim(ClaimTypes.Email, email));
                }
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            claims.AddRange(GetProfileClaims(userName));

            return claims;
        }
 public IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
 {
     return new List<Claim>
     {
         principal.Identities.First().FindFirst(ClaimTypes.Name),
         new Claim("http://claims/custom/foo", "bar")
     };
 }
        public IEnumerable<Claim> GetClaims(IClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var claims = from c in NewContext.UserClaims
                         where c.PartitionKey == principal.Identity.Name.ToLower() &&
                               c.Kind == UserClaimEntity.EntityKind
                         select new Claim(c.ClaimType, c.Value);

            return claims.ToList();
        }
        public RequestDetails Analyze(RequestSecurityToken rst, ClaimsPrincipal principal)
        {
            if (rst == null)
            {
                throw new ArgumentNullException("rst");
            }

            if (principal == null)
            {
                throw new ArgumentNullException("principal");
            }

            Tracing.Information("Starting PolicyOptions creation");

            var clientIdentity = AnalyzeClientIdentity(principal);

            var details = new RequestDetails
            {
                ClientIdentity = clientIdentity,
                IsActive = false,
                Realm = null,
                IsKnownRealm = false,
                UsesSsl = false,
                UsesEncryption = false,
                ReplyToAddress = null,
                ReplyToAddressIsWithinRealm = false,
                IsReplyToFromConfiguration = false,
                EncryptingCertificate = null,
                ClaimsRequested = false,
                RequestClaims = null,
                Request = null,
                IsActAsRequest = false,
                RelyingPartyRegistration = null
            };

            AnalyzeRst(rst, details);
            AnalyzeTokenType(rst, details);
            AnalyzeKeyType(rst);
            AnalyzeRealm(rst, details);
            AnalyzeOperationContext(details);
            AnalyzeDelegation(rst, details);
            AnalyzeRelyingParty(details);
            AnalyzeEncryption(details);
            AnalyzeReplyTo(details);
            AnalyzeSsl(details);
            AnalyzeRequestClaims(details);

            Tracing.Information("PolicyOptions creation done.");

            _details = details;
            return details;
        }
        public IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var claims = new List<Claim>();
            var nameClaim = principal.Identities.First().FindFirst(ClaimTypes.Name);
            claims.Add(nameClaim);
            var response = RewardService.GetRewardProgram(new GetRewardProgramRequest {UserName = nameClaim.Value});
            if(response != null)
            {
                claims.Add(new Claim("http://oceanicairlines.com/rewardlevel/", response.RewardLevel.ToString()));
            };

            return claims;
        }
        HttpResponseMessage Get()
        {
            var requestClaims = new RequestClaimCollection();

            var scopes = ClaimsPrincipal.Current.FindAll(OAuth2Constants.Scope);
            foreach (var scope in scopes)
            {
                if (OidcConstants.Mappings.ContainsKey(scope.Value))
                {
                    foreach (var oidcClaim in OidcConstants.Mappings[scope.Value])
                    {
                        requestClaims.Add(new RequestClaim(oidcClaim));
                    }
                }
                else
                {
                    Request.CreateErrorResponse(HttpStatusCode.BadRequest, "invalid scope");
                }
            }

            var details = new RequestDetails { IsOpenIdRequest = true };
            details.ClaimsRequested = true;
            details.RequestClaims = requestClaims;

            var principal = Principal.Create("OpenIdConnect",
                new Claim(ClaimTypes.NameIdentifier, ClaimsPrincipal.Current.FindFirst("sub").Value));

            var claims = ClaimsRepository.GetClaims(principal, details);

            var dictionary = new Dictionary<string, string>();
            foreach (var claim in claims)
            {
                if (!dictionary.ContainsKey(claim.Type))
                {
                    dictionary.Add(claim.Type, claim.Value);
                }
                else
                {
                    var currentValue = dictionary[claim.Type];
                    dictionary[claim.Type] = currentValue += ("," + claim.Value);
                }
            }

            return Request.CreateResponse<Dictionary<string, string>>(HttpStatusCode.OK, dictionary, "application/json");
        }
        public RequestDetailsScope(RequestDetails details, SigningCredentials signingCredentials, bool requireEncryption)
            : base(details.Realm.Uri.AbsoluteUri, signingCredentials)
        {
            RequestDetails = details;

            if (RequestDetails.UsesEncryption)
            {
                EncryptingCredentials = new X509EncryptingCredentials(details.EncryptingCertificate);
            }

            if (RequestDetails.TokenType == SimpleWebToken.OasisTokenProfile)
            {
                SigningCredentials = new SymmetricSigningCredentials(details.RelyingPartyRegistration.SymmetricSigningKey);
            }

            ReplyToAddress = RequestDetails.ReplyToAddress.AbsoluteUri;
            TokenEncryptionRequired = requireEncryption;
        }
        public HttpResponseMessage Get()
        {
            Tracing.Start("OIDC UserInfo endpoint");

            var details = new RequestDetails { IsOpenIdRequest = true };
            var scopeClaims = ClaimsPrincipal.Current.FindAll(OAuth2Constants.Scope).ToList();
            var requestedClaims = ClaimsPrincipal.Current.FindAll("requestclaim").ToList();

            if (scopeClaims.Count > 0)
            {
                var scopes = new List<string>(scopeClaims.Select(sc => sc.Value));
                details.OpenIdScopes = scopes;
            }

            if (requestedClaims.Count > 0)
            {
                var requestClaims = new RequestClaimCollection();
                requestedClaims.ForEach(rc => requestClaims.Add(new RequestClaim(rc.Value)));
                
                details.ClaimsRequested = true;
                details.RequestClaims = requestClaims;
            }

            var principal = Principal.Create("OpenIdConnect",
                new Claim(ClaimTypes.Name, ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value));

            var claims = ClaimsRepository.GetClaims(principal, details);

            var dictionary = new Dictionary<string, string>();
            foreach (var claim in claims)
            {
                if (!dictionary.ContainsKey(claim.Type))
                {
                    dictionary.Add(claim.Type, claim.Value);
                }
                else
                {
                    var currentValue = dictionary[claim.Type];
                    dictionary[claim.Type] = currentValue += ("," + claim.Value);
                }
            }

            return Request.CreateResponse<Dictionary<string, string>>(HttpStatusCode.OK, dictionary, "application/json");
        }
        public virtual IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            // email address
            string email = userName;
            if (!String.IsNullOrEmpty(email))
            {
                    claims.Add(new Claim(ClaimTypes.Email, email));                
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            claims.AddRange(GetProfileClaims(userName));
            return claims;
        }
        virtual public IEnumerable<Claim> GetClaims(IClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var claims = new List<Claim>();

            using (PrincipalContext context = GetPrincipalContext())
            {
                var userName = principal.Identity.Name;

                // find the user in the identity store
                UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);

                // email address
                string email = user.EmailAddress;
                if (!String.IsNullOrEmpty(email))
                {
                    claims.Add(new Claim(ClaimTypes.Email, email));
                }

                // roles
                GetRoles(userName, RoleTypes.Client).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

                // profile claims
                if (ProfileManager.Enabled)
                {
                    var profile = ProfileBase.Create(userName, true);
                    if (profile != null)
                    {
                        foreach (SettingsProperty prop in ProfileBase.Properties)
                        {
                            string value = profile.GetPropertyValue(prop.Name).ToString();
                            if (!String.IsNullOrWhiteSpace(value))
                            {
                                claims.Add(new Claim(ProfileClaimPrefix + prop.Name.ToLowerInvariant(), value));
                            }
                        }
                    }
                }
            }

            return claims;
        }
        public RequestDetailsScope(RequestDetails details, SigningCredentials signingCredentials, bool requireEncryption)
            : base(details.Realm.Uri.AbsoluteUri, signingCredentials)
        {
            RequestDetails = details;

            if (RequestDetails.UsesEncryption)
            {
                EncryptingCredentials = new X509EncryptingCredentials(details.EncryptingCertificate);
            }

            if (RequestDetails.TokenType == TokenTypes.SimpleWebToken || RequestDetails.TokenType == TokenTypes.JsonWebToken)
            {
                if (details.RelyingPartyRegistration.SymmetricSigningKey != null && details.RelyingPartyRegistration.SymmetricSigningKey.Length > 0)
                {
                    SigningCredentials = new HmacSigningCredentials(details.RelyingPartyRegistration.SymmetricSigningKey);
                }
            }

            ReplyToAddress = RequestDetails.ReplyToAddress.AbsoluteUri;
            TokenEncryptionRequired = requireEncryption;
        }
        public override IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            if (requestDetails.Realm.Uri.AbsoluteUri == "http://sbserver/swttest/")
            {
                if (principal.Identity.Name == "bob")
                {
                    return new List<Claim>
                    {
                        new Claim(sbClaimType, "Listen"),
                        new Claim(sbClaimType, "Manage"),
                    };
                }
                else
                {
                    return new List<Claim>
                    {
                        new Claim(sbClaimType, "Send"),
                    };
                }
            }

            return base.GetClaims(principal, requestDetails);
        }
        public IEnumerable<Claim> ProcessClaims(ClaimsPrincipal incomingPrincipal, IdentityProvider identityProvider, RequestDetails details)
        {
            var audienceUri = details.Realm.Uri.AbsoluteUri;
            var newClaimsPrincipal = (ClaimsIdentity)incomingPrincipal.Identity;
            newClaimsPrincipal.AddClaim(new Claim("http://schemas.fcsamerica.com/claims/PartnerApps/audienceuri", audienceUri));
            return newClaimsPrincipal.Claims;

            /*  Prototype code to test loading Claims Mapper Claims from STS.

            ClaimsIdentity claimsIdentity = incomingPrincipal.Identity as ClaimsIdentity;
            var emailClaim = incomingPrincipal.Claims.FirstOrDefault(_ => _.Type.Equals(ClaimTypes.Email));
               // var partnerClaim = incomingPrincipal.Claims.FirstOrDefault(_ => _.Type.Con)
               // NOTE: McGruff has a Get Partner Name from Host Header Method.
               // QUESTION:  How will we store the STS generated SAML token on the claims principal?  It isn't rewritten yet. We will need to generate it here?
               // QUESTION:  If the Audit Info is on the claims principal... We would still need logic to help people determine which one to pull.  Look at RequestHeader first, then Claims Principal.
               // QUESTION:  We still need an API for accessing SAML token and AuditInfo.   Can this be the Token Generator?
               // QUESTION:  How much of the WIF settings can be added to the Website Root for Inheritance?
               // QUESTION:  How can we call Claims Mapper Service without a SAML token.  - it hasn't been created yet. Or can we create a temporary one here????
            List<Claim> claims = new List<Claim>();
            if( emailClaim != null)
            {
                var emailAddress = emailClaim.Value;
                var realm = details.Realm.ToString();
                var applicationName = realm.Substring(realm.IndexOf(":")+1);

                // call claims mapper and add additional claims...
                claims.Add(new Claim("AuditInfo", "Test AuditInfo Value"));
            }
            else
            {
                claims.Add(new Claim("STSClaimsLoadError", "Could not determine the partner and/or application. Make sure the realm has the application name and IdP provides the partner claim."));
            }

            claimsIdentity.AddClaims(claims);
            return claimsIdentity.Claims;
            */
        }
 private void ValidateTokenType(RequestDetails details)
 {
     if (details.TokenType == TokenTypes.SimpleWebToken || details.TokenType == TokenTypes.JsonWebToken)
     {
         if (details.RelyingPartyRegistration == null ||
             details.RelyingPartyRegistration.SymmetricSigningKey == null ||
             details.RelyingPartyRegistration.SymmetricSigningKey.Length == 0)
         {
             Tracing.Error("Token with symmetric siganture requested, but no symmetric signing key found");
             throw new InvalidRequestException("Token with symmetric siganture requested, but no symmetric signing key found");
         }
     }
 }
 public IEnumerable<Claim> ProcessClaims(ClaimsPrincipal incomingPrincipal, IdentityProvider identityProvider, RequestDetails details)
 {
     return incomingPrincipal.Claims;
 }
 protected virtual void AnalyzeDelegation(RequestSecurityToken rst, RequestDetails details)
 {
     // check for identity delegation request
     if (rst.ActAs != null)
     {
         details.IsActAsRequest = true;
         Tracing.Information("Request is ActAs request");
     }
 }
 protected virtual void AnalyzeTokenType(RequestSecurityToken rst, RequestDetails details)
 {
     if (string.IsNullOrWhiteSpace(rst.TokenType))
     {
         details.TokenType = _configuration.DefaultTokenType;
         Tracing.Information("Token Type: not specified, falling back to default token type");
     }
     else
     {
         Tracing.Information("Token Type: " + rst.TokenType);
         details.TokenType = rst.TokenType;
     }
 }
        protected virtual RelyingParty AnalyzeRelyingParty(RequestDetails details)
        {
            // check if the relying party is registered
            RelyingParty rp = null;
            if (RelyingPartyRepository.TryGet(details.Realm.Uri.AbsoluteUri, out rp))
            {
                details.RelyingPartyRegistration = rp;
                details.IsKnownRealm = true;

                var traceString = String.Format("Relying Party found in registry - Realm: {0}", rp.Realm.AbsoluteUri);

                if (!string.IsNullOrEmpty(rp.Name))
                {
                    traceString += String.Format(" ({0})", rp.Name);
                }

                Tracing.Information(traceString);

                if (rp.EncryptingCertificate != null)
                {
                    details.EncryptingCertificate = rp.EncryptingCertificate;
                    Tracing.Information("Encrypting certificate set from registry");
                }
            }
            else
            {
                Tracing.Information("Relying party is not registered.");
            }
            return rp;
        }
 protected virtual void AnalyzeOperationContext(RequestDetails details)
 {
     // determine if this is a WCF call
     if (OperationContext.Current != null)
     {
         details.IsActive = true;
         Tracing.Information("Active request");
     }
     else
     {
         Tracing.Information("Passive request");
     }
 }
        public IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(System.Security.Claims.ClaimTypes.Role, role)));

            // profile claims
            claims.AddRange(GetProfileClaims(userName));

            //context claims 
            if (requestDetails.Request.AdditionalContext != null && requestDetails.Request.AdditionalContext.Items.Count() > 0)
            {
                //Aggiunta di Claim da parte del client questa logica serve per settare di lingua,company e profilo

                var passedProfile = requestDetails.Request.AdditionalContext.Items.FirstOrDefault(p => p.Name.ToString() == Sagrada.IdentityServer.ClaimTypes.Profile);
                if (passedProfile != null)
                {
                    var profiles = SagradaIdentityService.GetProfiles(userName);
                    if (profiles.Count(p => p.Item1.ToString() == passedProfile.Value) == 0)
                    {
                        string errors = string.Format("additionalContext request from {0} has a not valid claim : {1}.", requestDetails.Realm.Uri, Sagrada.IdentityServer.ClaimTypes.Profile);
                        Tracing.Error(errors);
                        throw new InvalidRequestException(errors);
                    }
                    else
                        claims.Add(new Claim(Sagrada.IdentityServer.ClaimTypes.Profile, passedProfile.Value));
                }
                
                var passedCompany = requestDetails.Request.AdditionalContext.Items.FirstOrDefault(p => p.Name.ToString() == Sagrada.IdentityServer.ClaimTypes.Company);
                if (passedCompany != null)
                {
                    var companies = SagradaIdentityService.GetCompanies();
                    if (companies.Count(p => p.Item1.ToString() == passedCompany.Value) == 0)
                    {
                        string errors = string.Format("additionalContext request from {0} has a not valid claim : {1}.", requestDetails.Realm.Uri, Sagrada.IdentityServer.ClaimTypes.Company);
                        Tracing.Error(errors);
                        throw new InvalidRequestException(errors);
                    }
                    else
                        claims.Add(new Claim(Sagrada.IdentityServer.ClaimTypes.Company, passedCompany.Value));
                }
            
                var passedLanguage = requestDetails.Request.AdditionalContext.Items.FirstOrDefault(p => p.Name.ToString() == Sagrada.IdentityServer.ClaimTypes.Language);
                if (passedLanguage != null)
                {
                    var languages = SagradaIdentityService.GetLanguages();
                    if (languages.Count(p => p.Name == passedLanguage.Value) == 0)
                    {
                        string errors = string.Format("additionalContext request from {0} has a not valid claim : {1}.", requestDetails.Realm.Uri, Sagrada.IdentityServer.ClaimTypes.Language);
                        Tracing.Error(errors);
                        throw new InvalidRequestException(errors);
                    }
                    else
                        claims.Add(new Claim(Sagrada.IdentityServer.ClaimTypes.Language, passedLanguage.Value));
                }
            
            };

            return claims;
        }
 protected virtual void AnalyzeSsl(RequestDetails details)
 {
     // determine if reply to is via SSL
     details.UsesSsl = (details.ReplyToAddress.Scheme == Uri.UriSchemeHttps);
     Tracing.Information(String.Format("SSL used:{0}", details.UsesSsl));
 }
        protected virtual void ValidateDelegation(RequestDetails details)
        {
            // check for ActAs request
            if (details.IsActAsRequest)
            {
                if (!_configuration.EnableDelegation)
                {
                    Tracing.Error("Request is ActAs request - but ActAs is not enabled");
                    throw new InvalidRequestException("Request is ActAs request - but ActAs is not enabled");
                }

                if (!DelegationRepository.IsDelegationAllowed(details.ClientIdentity.Name, details.Realm.Uri.AbsoluteUri))
                {
                    Tracing.Error(String.Format("ActAs mapping not found."));
                    throw new InvalidRequestException("ActAs mapping not found.");
                }
            }
        }
        protected virtual void AnalyzeRealm(RequestSecurityToken rst, RequestDetails options)
        {
            // check realm
            if (rst.AppliesTo == null || rst.AppliesTo.Uri == null)
            {
                throw new Exception("AppliesTo is missing");
                //throw new MissingAppliesToException("AppliesTo is missing");
            }

            options.Realm = new EndpointAddress(rst.AppliesTo.Uri);
        }
        protected virtual void AnalyzeRst(RequestSecurityToken rst, RequestDetails options)
        {
            if (rst == null)
            {
                throw new ArgumentNullException("request");
            }

            options.Request = rst;
        }
 protected virtual void ValidateEncryption(RequestDetails details)
 {
     // check if token must be encrypted
     if (_configuration.RequireEncryption && (!details.UsesEncryption))
     {
         Tracing.Error("Configuration requires encryption - but no key available");
         throw new InvalidRequestException("No encryption key available");
     }
 }
 protected virtual void ValidateReplyTo(RequestDetails details)
 {
     // check if replyto is part of a registered realm (when not explicitly registered in config)
     if (!details.IsReplyToFromConfiguration)
     {
         if (_configuration.RequireReplyToWithinRealm && (!details.ReplyToAddressIsWithinRealm))
         {
             Tracing.Error("Configuration requires that ReplyTo is a sub-address of the realm - this is not the case");
             throw new InvalidRequestException("Invalid ReplyTo");
         }
     }
 }
        public IEnumerable<System.Security.Claims.Claim> GetClaims(
            ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var user = userSvc.GetByUsername(principal.Identity.Name);
            if (user == null) throw new ArgumentException("Invalid Username");

            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, user.Username));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.ID.ToString("D")));
            if (!String.IsNullOrWhiteSpace(user.Email))
            {
                claims.Add(new Claim(ClaimTypes.Email, user.Email));
            }
            if (!String.IsNullOrWhiteSpace(user.MobilePhoneNumber))
            {
                claims.Add(new Claim(ClaimTypes.MobilePhone, user.MobilePhoneNumber));
            }
            //var x509 = from c in user.Certificates
            //           select new Claim(ClaimTypes.X500DistinguishedName, c.Subject);
            //claims.AddRange(x509);
            var otherClaims =
                (from uc in user.Claims
                 select new Claim(uc.Type, uc.Value)).ToList();
            claims.AddRange(otherClaims);

            return claims;
        }
        protected virtual void ValidateKnownRealm(RequestDetails details)
        {
            // check if realm is allowed
            if (_configuration.AllowKnownRealmsOnly && (!details.IsKnownRealm))
            {
                Tracing.Error("Configuration requires a known realm - but realm is not registered");

                throw new Exception(details.Realm.Uri.AbsoluteUri);
                //throw new InvalidScopeException(details.Realm.Uri.AbsoluteUri);
            }
        }
 protected virtual void ValidateSsl(RequestDetails details)
 {
     // check if SSL is used (for passive only)
     if (_configuration.RequireSsl && !details.UsesSsl)
     {
         if (!details.IsActive)
         {
             Tracing.Error("Configuration requires SSL - but clear text reply address used");
             throw new InvalidRequestException("SSL is required");
         }
     }
 }
        protected virtual void AnalyzeEncryption(RequestDetails details)
        {
            if (details.EncryptingCertificate == null)
            {
                X509Certificate2 requestCertificate;
                if (TryGetEncryptionCertificateFromRequest(details.Realm, out requestCertificate))
                {
                    details.EncryptingCertificate = requestCertificate;
                    Tracing.Information("Encrypting certificate set from RST");
                }
            }

            details.UsesEncryption = (details.EncryptingCertificate != null);
            Tracing.Information("Token encryption: " + details.UsesEncryption);
        }