public void SecurityTokenHandlerCollectionExtensions_Publics()
        {
            SecurityTokenHandlerCollection securityTokenValidators = new SecurityTokenHandlerCollection();
            string defaultSamlToken  = IdentityUtilities.CreateSamlToken();
            string defaultSaml2Token = IdentityUtilities.CreateSaml2Token();
            string defaultJwt        = IdentityUtilities.DefaultAsymmetricJwt;

            ExpectedException expectedException = ExpectedException.ArgumentNullException("Parameter name: securityToken");

            ValidateToken(null, null, securityTokenValidators, expectedException);

            expectedException = ExpectedException.ArgumentNullException("Parameter name: validationParameters");
            ValidateToken(defaultSamlToken, null, securityTokenValidators, expectedException);

            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters();

            expectedException = ExpectedException.SecurityTokenValidationException("IDX10201");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            expectedException       = ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators.Clear();
            securityTokenValidators.Add(new IMSamlTokenHandler());
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:"));
            ValidateToken(defaultSamlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.SecurityTokenValidationException(substringExpected: "IDX10201:"));
            securityTokenValidators.Add(new IMSaml2TokenHandler());
            securityTokenValidators.Add(new System.IdentityModel.Tokens.JwtSecurityTokenHandler());
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultJwt, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
        }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            // <!-- IssuerName Configuration - ha50idpm2 -->
            string idpEntityId = WebConfigurationManager.AppSettings["IdpEntityId"];
            CustomSecurityTokenServiceConfiguration config = new CustomSecurityTokenServiceConfiguration(idpEntityId);

            // Create a security token handler collection and then provide with a SAML2 security token
            // handler and set the Audience restriction to Never
            SecurityTokenHandlerCollection onBehalfOfHandlers = new SecurityTokenHandlerCollection();
            OnBehalfOfSaml2SecurityTokenHandler onBehalfOfTokenHandler = new OnBehalfOfSaml2SecurityTokenHandler();

            onBehalfOfHandlers.Add(onBehalfOfTokenHandler);

            // Do not process the Audience in the incoming OnBehalfOf token since this token
            // is not for authenticating with the ADS
            onBehalfOfHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

            // Set the appropriate issuer name registry
            onBehalfOfHandlers.Configuration.IssuerNameRegistry = new IdpAdsIssuerNameRegistry();

            // Set the token handlers collection
            config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.OnBehalfOf] = onBehalfOfHandlers;
            
            WSTrustServiceHost host = new WSTrustServiceHost(config, baseAddresses);

            host.Description.Endpoints[0].Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

            return host;
        }        
예제 #3
0
    public CardSignIn()
    {
        SecurityTokenHandlerConfiguration handlerConfig = new SecurityTokenHandlerConfiguration();

        handlerConfig.IssuerNameRegistry = new TrustedIssuerNameRegistry();

        List <SecurityToken> servicetokens = new List <SecurityToken>(1);

        servicetokens.Add(new X509SecurityToken(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=localhost")));
        handlerConfig.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(servicetokens.AsReadOnly(), false);

        handlerConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://localhost/AuthAssuranceSTS/CardSignIn.aspx"));

        _handlers = new SecurityTokenHandlerCollection(handlerConfig);

        SamlSecurityTokenRequirement samlReqs = new SamlSecurityTokenRequirement();

        _handlers.Add(new EncryptedSecurityTokenHandler());
        _handlers.Add(new Saml11SecurityTokenHandler(samlReqs));
    }
    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
    {
        StreamWriter file = new StreamWriter("c:\\temp\\IdentityProviderSts.OnBehalfOfSecurityTokenServiceFactory - CreateServiceHost.txt", true);
        file.WriteLine("_________________________________________");
        file.WriteLine("DateTime: " + DateTime.Now.ToString());

        file.WriteLine("constructorString:" + constructorString);
        file.Close();


        SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration("https://ha50idp:8544/IDP-STS/Issue.svc");

        //Uri baseUri = baseAddresses.FirstOrDefault(a => a.Scheme == "https");
        //if (baseUri == null)
        //    throw new InvalidOperationException("The STS should be hosted under https");

        //config.TrustEndpoints.Add(new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetCertificateCredentialsBinding(), baseUri + ""));
        
        // Set the STS implementation class type
        config.SecurityTokenService = typeof(CustomSecurityTokenService);

        // Create a security token handler collection and then provide with a SAML11 security token
        // handler and set the Audience restriction to Never
        SecurityTokenHandlerCollection onBehalfOfHandlers = new SecurityTokenHandlerCollection();
        Saml2SecurityTokenHandler onBehalfOfTokenHandler = new Saml2SecurityTokenHandler();
        
        onBehalfOfHandlers.Add(onBehalfOfTokenHandler);
        //onBehalfOfHandlers.Add(userNameTokenHandler);
        onBehalfOfHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

        // Set the appropriate issuer name registry
        //onBehalfOfHandlers.Configuration.IssuerNameRegistry = new IdentityProviderIssuerNameRegistry();

        // Set the token handlers collection
        config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.OnBehalfOf] = onBehalfOfHandlers;

//        WindowsUserNameSecurityTokenHandler userNameTokenHandler = new WindowsUserNameSecurityTokenHandler();
//        config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.Default].Add(userNameTokenHandler);
        
        WSTrustServiceHost host = new WSTrustServiceHost(config, baseAddresses);        
        return host;
    }
        /// <summary>
        /// Loads the <see cref="SecurityTokenHandlerCollectionManager"/> defined for a given service.
        /// </summary>
        /// <param name="serviceElement">The <see cref="IdentityConfigurationElement"/> used to configure this instance.</param>
        /// <returns></returns>
        protected SecurityTokenHandlerCollectionManager LoadHandlers(IdentityConfigurationElement serviceElement)
        {
            //
            // We start with a token handler collection manager that contains a single collection that includes the default
            // handlers for the system.
            //
            SecurityTokenHandlerCollectionManager manager = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            if (serviceElement != null)
            {
                //
                // Load any token handler collections that appear as part of this service element
                //
                if (serviceElement.SecurityTokenHandlerSets.Count > 0)
                {
                    foreach (SecurityTokenHandlerElementCollection handlerElementCollection in serviceElement.SecurityTokenHandlerSets)
                    {
                        try
                        {
                            SecurityTokenHandlerConfiguration handlerConfiguration;
                            SecurityTokenHandlerCollection handlerCollection;

                            if (string.IsNullOrEmpty(handlerElementCollection.Name) ||
                                 StringComparer.Ordinal.Equals(handlerElementCollection.Name, ConfigurationStrings.DefaultConfigurationElementName))
                            {
                                //
                                // For the default collection, merge the IdentityConfiguration with the underlying config, if it exists.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    //
                                    // Configuration from a nested configuration object. We start with Service level configuration for 
                                    // handlers and then override the collection specific configuration. The result is a new configuration
                                    // object that can only be modified by accessing the collection or handlers configuration properties.
                                    //
                                    _serviceHandlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                    handlerConfiguration = LoadHandlerConfiguration(_serviceHandlerConfiguration, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // No nested configuration object. We use the values from the ServiceElement for this case.
                                    //
                                    handlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                }

                                _serviceHandlerConfiguration = handlerConfiguration;
                            }
                            else
                            {
                                //
                                // This is a non-default collection. There should be no settings inherited from IdentityConfiguration.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    handlerConfiguration = LoadHandlerConfiguration(null, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // If there is no underlying config, set everything as default.
                                    //
                                    handlerConfiguration = new SecurityTokenHandlerConfiguration();
                                }
                            }

                            handlerCollection = new SecurityTokenHandlerCollection(handlerConfiguration);
                            manager[handlerElementCollection.Name] = handlerCollection;

                            foreach (CustomTypeElement handlerElement in handlerElementCollection)
                            {
                                handlerCollection.Add(CustomTypeElement.Resolve<SecurityTokenHandler>(handlerElement));
                            }
                        }
                        catch (ArgumentException inner)
                        {
                            throw DiagnosticUtility.ThrowHelperConfigurationError(serviceElement, handlerElementCollection.Name, inner);
                        }
                    }
                }
                //
                // Ensure that the default usage collection always exists
                //
                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }
            else
            {
                //
                // Ensure that the default usage collection always exists
                //
                _serviceHandlerConfiguration = new SecurityTokenHandlerConfiguration();

                _serviceHandlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;

                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }

            return manager;
        }
        public void SecurityTokenHandlerCollectionExtensions_Publics()
        {
            SecurityTokenHandlerCollection securityTokenValidators = new SecurityTokenHandlerCollection();
            string defaultSamlToken = IdentityUtilities.CreateSamlToken();
            string defaultSaml2Token = IdentityUtilities.CreateSaml2Token();
            string defaultJwt = IdentityUtilities.DefaultAsymmetricJwt;

            ExpectedException expectedException = ExpectedException.ArgumentNullException("Parameter name: securityToken");
            ValidateToken(null, null, securityTokenValidators, expectedException);

            expectedException = ExpectedException.ArgumentNullException("Parameter name: validationParameters");
            ValidateToken(defaultSamlToken, null, securityTokenValidators, expectedException);

            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters();
            expectedException = ExpectedException.SecurityTokenValidationException("IDX10201");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            expectedException = ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators.Clear();
            securityTokenValidators.Add(new IMSamlTokenHandler());
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:"));
            ValidateToken(defaultSamlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.SecurityTokenValidationException(substringExpected: "IDX10201:"));
            securityTokenValidators.Add(new IMSaml2TokenHandler());
            securityTokenValidators.Add(new System.IdentityModel.Tokens.JwtSecurityTokenHandler());
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultJwt, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
        }
        public ActionResult Authenticate(string ReturnUrl)
        {
            if (Request.Form.Get(WSFederationConstants.Parameters.Result) != null)
            {
                var settings = this.SettingsService.Retrieve();

                // Parse sign-in response
                SignInResponseMessage message =
                    WSFederationMessage.CreateFromFormPost(System.Web.HttpContext.Current.Request) as
                    SignInResponseMessage;

                XmlTextReader xmlReader = new XmlTextReader(
                    new StringReader(message.Result));
                XDocument  xDoc = XDocument.Load(xmlReader);
                XNamespace xNs  = "http://schemas.xmlsoap.org/ws/2005/02/trust";
                var        rst  = xDoc.Descendants(xNs + "RequestedSecurityToken").FirstOrDefault();
                if (rst == null)
                {
                    throw new ApplicationException("No RequestedSecurityToken element was found in the returned XML token. Ensure an unencrypted SAML 2.0 token is issued.");
                }
                var rstDesc = rst.Descendants().FirstOrDefault();
                if (rstDesc == null)
                {
                    throw new ApplicationException("No valid RequestedSecurityToken element was found in the returned XML token. Ensure an unencrypted SAML 2.0 token is issued.");
                }

                var config = new SecurityTokenHandlerConfiguration();
                config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(settings.AudienceUrl));
                config.CertificateValidator = X509CertificateValidator.None;
                config.IssuerNameRegistry   = new AccessControlServiceIssuerRegistry(
                    settings.StsIssuerUrl, settings.X509CertificateThumbprint);

                var securityTokenHandlers = new SecurityTokenHandlerCollection(config);
                securityTokenHandlers.Add(new Saml11SecurityTokenHandler());
                securityTokenHandlers.Add(new Saml2SecurityTokenHandler());
                securityTokenHandlers.Add(new EncryptedSecurityTokenHandler());

                var token = securityTokenHandlers.ReadToken(rstDesc.CreateReader());

                ClaimsIdentityCollection claims = securityTokenHandlers.ValidateToken(token);
                IPrincipal principal            = new ClaimsPrincipal(claims);

                // Map claims to local users
                string roleClaimValue     = "";
                string usernameClaimValue = "";
                string emailClaimValue    = "";
                foreach (var claimsIdentity in claims)
                {
                    foreach (var claim in claimsIdentity.Claims)
                    {
                        if (claim.ClaimType == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" && settings.TranslateClaimsToOrchardRoles)
                        {
                            roleClaimValue = claim.Value;
                        }
                        else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" && settings.TranslateClaimsToOrchardUserProperties)
                        {
                            emailClaimValue = claim.Value;
                        }
                        else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")
                        {
                            usernameClaimValue = claim.Value;
                        }
                        else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" && string.IsNullOrEmpty(usernameClaimValue))
                        {
                            usernameClaimValue = claim.Value;
                        }
                    }
                }

                if (string.IsNullOrEmpty(usernameClaimValue))
                {
                    throw new SecurityException("Could not determine username from input claims. Ensure a \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\" or \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier\" claim is issued by the STS.");
                }

                IUser user = MembershipService.GetUser(settings.FederatedUsernamePrefix + usernameClaimValue);
                if (user == null)
                {
                    user = MembershipService.CreateUser(new CreateUserParams(settings.FederatedUsernamePrefix + usernameClaimValue,
                                                                             Guid.NewGuid().ToString(), emailClaimValue,
                                                                             Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true));
                }

                AuthenticationService.SignIn(user, false);

                if (!string.IsNullOrEmpty(roleClaimValue))
                {
                    var role = RoleService.GetRoleByName(roleClaimValue);
                    if (role != null)
                    {
                        UserRolesPartRecord currentRole =
                            UserRolesRepository.Get(r => r.UserId == user.Id && r.Role == role);
                        if (currentRole == null)
                        {
                            UserRolesRepository.Create(new UserRolesPartRecord {
                                UserId = user.Id, Role = role
                            });
                        }
                    }
                }
            }

            return(new RedirectResult(ReturnUrl));
        }
예제 #8
0
        /// <summary>
        /// Loads the <see cref="SecurityTokenHandlerCollectionManager"/> defined for a given service.
        /// </summary>
        /// <param name="serviceElement">The <see cref="IdentityConfigurationElement"/> used to configure this instance.</param>
        /// <returns></returns>
        protected SecurityTokenHandlerCollectionManager LoadHandlers(IdentityConfigurationElement serviceElement)
        {
            //
            // We start with a token handler collection manager that contains a single collection that includes the default
            // handlers for the system.
            //
            SecurityTokenHandlerCollectionManager manager = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            if (serviceElement != null)
            {
                //
                // Load any token handler collections that appear as part of this service element
                //
                if (serviceElement.SecurityTokenHandlerSets.Count > 0)
                {
                    foreach (SecurityTokenHandlerElementCollection handlerElementCollection in serviceElement.SecurityTokenHandlerSets)
                    {
                        try
                        {
                            SecurityTokenHandlerConfiguration handlerConfiguration;
                            SecurityTokenHandlerCollection    handlerCollection;

                            if (string.IsNullOrEmpty(handlerElementCollection.Name) ||
                                StringComparer.Ordinal.Equals(handlerElementCollection.Name, ConfigurationStrings.DefaultConfigurationElementName))
                            {
                                //
                                // For the default collection, merge the IdentityConfiguration with the underlying config, if it exists.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    //
                                    // Configuration from a nested configuration object. We start with Service level configuration for
                                    // handlers and then override the collection specific configuration. The result is a new configuration
                                    // object that can only be modified by accessing the collection or handlers configuration properties.
                                    //
                                    _serviceHandlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                    handlerConfiguration         = LoadHandlerConfiguration(_serviceHandlerConfiguration, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // No nested configuration object. We use the values from the ServiceElement for this case.
                                    //
                                    handlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                }

                                _serviceHandlerConfiguration = handlerConfiguration;
                            }
                            else
                            {
                                //
                                // This is a non-default collection. There should be no settings inherited from IdentityConfiguration.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    handlerConfiguration = LoadHandlerConfiguration(null, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // If there is no underlying config, set everything as default.
                                    //
                                    handlerConfiguration = new SecurityTokenHandlerConfiguration();
                                }
                            }

                            handlerCollection = new SecurityTokenHandlerCollection(handlerConfiguration);
                            manager[handlerElementCollection.Name] = handlerCollection;

                            foreach (CustomTypeElement handlerElement in handlerElementCollection)
                            {
                                handlerCollection.Add(CustomTypeElement.Resolve <SecurityTokenHandler>(handlerElement));
                            }
                        }
                        catch (ArgumentException inner)
                        {
                            throw DiagnosticUtility.ThrowHelperConfigurationError(serviceElement, handlerElementCollection.Name, inner);
                        }
                    }
                }
                //
                // Ensure that the default usage collection always exists
                //
                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }
            else
            {
                //
                // Ensure that the default usage collection always exists
                //
                _serviceHandlerConfiguration = new SecurityTokenHandlerConfiguration();

                _serviceHandlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;

                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }

            return(manager);
        }