public void Validate(Saml2SecurityToken token, SecurityTokenHandlerConfiguration configuration)
        {
            if (token == null || token.RawResponse == null ||
                configuration == null)
            {
                throw new ArgumentNullException();
            }

            // search for signatures (possibly multiple)
            var signatureNodes = token.RawResponse.GetElementsByTagName("Signature", Namespaces.XMLDSIG);

            foreach (XmlElement signatureNode in signatureNodes)
            {
                var signedXml = new SignedXml(signatureNode.ParentNode as XmlElement);
                signedXml.LoadXml(signatureNode);
                signedXml.SafeCanonicalizationMethods.Add("http://www.w3.org/TR/1999/REC-xpath-19991116");

                var result = signedXml.CheckSignature();

                if (!result)
                {
                    throw new ValidationException("Token's signature validation failed");
                }
            }
        }
Exemple #2
0
        public void Validate(Saml2SecurityToken token, SecurityTokenHandlerConfiguration configuration)
        {
            if (token == null || token.Response == null || configuration == null)
            {
                throw new ArgumentNullException();
            }

            if (token.Response.Assertions != null)
            {
                foreach (var assertion in token.Response.Assertions)
                {
                    if (assertion.Conditions != null)
                    {
                        ValidateNotBefore(assertion.Conditions.NotBefore, configuration.MaxClockSkew);
                        ValidateNotOnOrAfter(assertion.Conditions.NotOnOrAfter, configuration.MaxClockSkew);
                    }
                    if (
                        assertion.Subject != null &&
                        assertion.Subject.SubjectConfirmation != null &&
                        assertion.Subject.SubjectConfirmation.SubjectConfirmationData != null
                        )
                    {
                        ValidateNotBefore(assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotBefore, configuration.MaxClockSkew);
                        ValidateNotOnOrAfter(assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotOnOrAfter, configuration.MaxClockSkew);
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            //
            // Create a SAML token signed with the given certificate
            //
            byte[]             clientCertificateBytes = ManagementServiceHelper.ReadBytesFromPfxFile(ClientCertificateFilePath, ClientCertificatePassword);
            Saml2SecurityToken token = SelfSignedSaml2TokenGenerator.GetSamlAssertionSignedWithCertificate(ClientName, clientCertificateBytes, ClientCertificatePassword);

            //
            // Encode the SAML token into an OAuth request to ACS.
            //
            Dictionary <string, string> requestParameters = new Dictionary <string, string>();

            requestParameters[OAuth2Constants.Scope]     = ConfigurationManager.AppSettings.Get("RelyingPartyScope");
            requestParameters[OAuth2Constants.GrantType] = WifTokenTypes.Saml2TokenProfile11;
            requestParameters[OAuth2Constants.Assertion] = GetSaml2TokenString(token);

            Dictionary <string, string> acsResponse = GetOAuth2ResponseFromAcs(requestParameters);

            //
            // Pass the access token returned by ACS to the protected resource.
            //
            Console.WriteLine(GetProtectedResource(acsResponse[OAuth2Constants.AccessToken]));

            Console.WriteLine("Press <ENTER> to exit...");
            Console.ReadLine();
        }
Exemple #4
0
        public void ShouldWriterSamlResponseAssertionElement()
        {
            var issuer    = new Saml2NameIdentifier("issuer");
            var assertion = new Saml2Assertion(issuer)
            {
                Subject = new Saml2Subject(new Saml2NameIdentifier("subject"))
            };

            var token = new Saml2SecurityToken(assertion);

            var response = new SamlResponse
            {
                SecurityToken = token
            };

            var serialized = _serializer.SerializeSamlResponse(response);

            Assert.NotNull(serialized);

            var doc  = XDocument.Parse(serialized);
            var root = doc.Root;

            _mockHandler.Verify(h => h.WriteToken(It.IsAny <XmlWriter>(), token), Times.Once());
            var element = root.Element(XName.Get("Assertion", _assertionNamespace));

            Assert.NotNull(element);
        }
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            SecurityToken  securityToken;
            Saml2Assertion saml2Assertion;

            if (base.TokenRequirement.KeyType == SecurityKeyType.SymmetricKey)
            {
                securityToken  = SamlSecurityTokenProvider.CreateSymmetricProofToken(base.TokenRequirement.KeySize);
                saml2Assertion = this.CreateSamlAssertionWithSymmetricKey((BinarySecretSecurityToken)securityToken);
            }
            else
            {
                if (base.TokenRequirement.KeyType != SecurityKeyType.AsymmetricKey)
                {
                    throw new ArgumentOutOfRangeException("KeyType");
                }
                securityToken  = SamlSecurityTokenProvider.CreateAsymmetricProofToken();
                saml2Assertion = this.CreateSamlAssertionWithAsymmetricKey(securityToken);
            }
            Saml2SecurityToken saml2SecurityToken = new Saml2SecurityToken(saml2Assertion);
            XmlDocument        xmlDocument        = new XmlDocument();

            using (XmlWriter xmlWriter = xmlDocument.CreateNavigator().AppendChild())
            {
                Saml2SecurityTokenHandler saml2SecurityTokenHandler = new Saml2SecurityTokenHandler();
                saml2SecurityTokenHandler.WriteToken(xmlWriter, saml2SecurityToken);
            }
            SamlAssertionKeyIdentifierClause samlAssertionKeyIdentifierClause = saml2SecurityToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>();

            return(new GenericXmlSecurityToken(xmlDocument.DocumentElement, securityToken, saml2Assertion.Conditions.NotBefore.Value, saml2Assertion.Conditions.NotOnOrAfter.Value, samlAssertionKeyIdentifierClause, samlAssertionKeyIdentifierClause, null));
        }
        /// <summary>
        /// Creates a <see cref="ClaimsIdentity"/> from the Saml2 token.
        /// </summary>
        /// <param name="samlToken">The Saml2SecurityToken.</param>
        /// <param name="issuer">the issuer value for each <see cref="Claim"/> in the <see cref="ClaimsIdentity"/>.</param>
        /// <param name="validationParameters"> contains parameters for validating the token.</param>
        /// <returns>An IClaimIdentity.</returns>
        protected virtual ClaimsIdentity CreateClaimsIdentity(Saml2SecurityToken samlToken, string issuer, TokenValidationParameters validationParameters)
        {
            if (samlToken == null)
            {
                throw new ArgumentNullException("samlToken");
            }

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

            if (string.IsNullOrWhiteSpace(issuer))
            {
                throw new ArgumentException(ErrorMessages.IDX10221);
            }

            Saml2Assertion assertion = samlToken.Assertion;

            if (assertion == null)
            {
                throw new ArgumentException(ErrorMessages.IDX10202);
            }

            ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(samlToken, issuer);

            _smSaml2HandlerPrivateNeverSetAnyProperties.ProcessSamlSubjectPublic(samlToken.Assertion.Subject, identity, issuer);
            _smSaml2HandlerPrivateNeverSetAnyProperties.ProcessStatmentPublic(samlToken.Assertion.Statements, identity, issuer);
            return(identity);
        }
        public void Validate(Saml2SecurityToken token, SecurityTokenHandlerConfiguration configuration)
        {
            if (token == null || token.Response == null ||
                configuration == null)
            {
                throw new ArgumentNullException();
            }
            if (configuration.IssuerNameRegistry == null)
            {
                throw new ArgumentNullException("configuration", "Issuer name registry cannot empty in the configuration");
            }

            if (token.Response.Assertions != null)
            {
                foreach (var assertion in token.Response.Assertions)
                {
                    var securityToken = assertion.GetX509SecurityToken();
                    if (securityToken != null)
                    {
                        var issuer = configuration.IssuerNameRegistry.GetIssuerName(securityToken);
                        if (string.IsNullOrEmpty(issuer))
                        {
                            throw new ValidationException("Issuer name registry doesn't recognize token's certificate");
                        }
                    }
                }
            }
        }
Exemple #8
0
 private void OutputToken(Saml2SecurityTokenHandler handler, Saml2SecurityToken token)
 {
     Assert.NotNull(token);
     _output.WriteLine("SAML assertion:");
     if (token == null)
     {
         _output.WriteLine("null");
         return;
     }
     using (var inner = new StringWriter())
     {
         var settings = new XmlWriterSettings
         {
             OmitXmlDeclaration  = true,
             Indent              = true,
             NewLineOnAttributes = false,
             Encoding            = new UTF8Encoding(false)
         };
         using (var writer = XmlWriter.Create(inner, settings))
         {
             handler.WriteToken(writer, token);
         }
         _output.WriteLine(inner.ToString());
     }
 }
Exemple #9
0
        private void CreateSaml2Tokens(SecurityTokenDescriptor tokenDescriptor)
        {
            Saml2SecurityTokenHandler samlTokenHandler = new Saml2SecurityTokenHandler();
            Saml2SecurityToken        token            = samlTokenHandler.CreateToken(tokenDescriptor) as Saml2SecurityToken;
            MemoryStream        ms     = new MemoryStream();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms);

            samlTokenHandler.WriteToken(writer, token);
        }
Exemple #10
0
		private void PrintSaml2Token(Saml2SecurityToken token)
		{
			var sb = new StringBuilder();
			var xmlWriter = XmlWriter.Create(sb, new XmlWriterSettings{Indent = true});

			_saml2SecurityTokenHandler.WriteToken(xmlWriter, token);
			xmlWriter.Close();

			Console.WriteLine(sb.ToString());
		}
Exemple #11
0
 /// <summary>
 /// Creates a success result.
 /// </summary>
 /// <param name="partnerId">The id of the Saml2p SSO partner.</param>
 /// <param name="token">The <see cref="Saml2SecurityToken"/> from a <see cref="SamlResponse"/>.</param>
 /// <param name="subject">The <see cref="ClaimsPrincipal"/> that was created from <paramref name="token"/>.</param>
 /// <returns>A success result.</returns>
 public static FinishSsoResult Success(string partnerId, Saml2SecurityToken token, ClaimsPrincipal subject)
 {
     return(new FinishSsoResult
     {
         Status = Saml2pConstants.Statuses.Success,
         PartnerId = partnerId,
         SecurityToken = token,
         Subject = subject
     });
 }
Exemple #12
0
        private void WriteRequestedSecurityToken(XmlWriter writer, Saml2SecurityToken token)
        {
            writer.WriteStartElement("t", "RequestedSecurityToken", WsTrust200502Namespace);

            Saml2Serializer serializer = new Saml2Serializer();

            serializer.WriteAssertion(writer, token.Assertion);

            writer.WriteEndElement();
        }
Exemple #13
0
        // public static SamlSecurityToken CreateSamlSecurityToken(byte[] certificate, string password, params Claim[] claims)
        // {
        //    const string acsUrl = "http://blueprintsys.com";

        // var assertion = new SamlAssertion(new SamlNameIdentifier(DefaultIssuer));

        // var conditions = new Saml2Conditions
        //    {
        //        NotBefore = DateTime.UtcNow,
        //        NotOnOrAfter = DateTime.MaxValue
        //    };
        //    conditions.AudienceRestrictions.Add(new Saml2AudienceRestriction(new Uri(acsUrl, UriKind.RelativeOrAbsolute)));
        //    assertion.Conditions = conditions;

        // var subject = new Saml2Subject();
        //    subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(Bearer));
        //    assertion.Subject = subject;

        // var statement = new Saml2AttributeStatement();
        //    foreach (var claim in claims)
        //    {
        //        statement.Attributes.Add(new Saml2Attribute(claim.Type, claim.Value));
        //        assertion.Statements.Add(statement);
        //    }

        // var clientSigningCredentials = new X509SigningCredentials(
        //            new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable));

        // assertion.SigningCredentials = clientSigningCredentials;

        // return new Saml2SecurityToken(assertion);
        // }

        public static string Serialize(Saml2SecurityToken token)
        {
            var handler = new Saml2SecurityTokenHandler();
            var sw      = I18NHelper.CreateStringWriterInvariant();

            using (var textWriter = new XmlTextWriter(sw))
            {
                handler.WriteToken(textWriter, token);
                return(sw.ToString());
            }
        }
        /// <summary>
        /// Create claims from the token.
        /// </summary>
        /// <param name="samlToken">The token to translate to claims.</param>
        /// <returns>An identity with the created claims.</returns>
        protected override ClaimsIdentity CreateClaimsIdentity(Saml2SecurityToken samlToken, string issuer, TokenValidationParameters validationParameters)
        {
            var identity = base.CreateClaimsIdentity(samlToken, issuer, validationParameters);

            if (Configuration.SaveBootstrapContext)
            {
                identity.BootstrapContext = new BootstrapContext(samlToken, this);
            }

            return(identity);
        }
        /// <summary>
        /// Create claims from the token.
        /// </summary>
        /// <param name="samlToken">The token to translate to claims.</param>
        /// <returns>An identity with the created claims.</returns>
        public new ClaimsIdentity CreateClaims(Saml2SecurityToken samlToken)
        {
            var identity = base.CreateClaims(samlToken);

            if (Configuration.SaveBootstrapContext)
            {
                identity.BootstrapContext = new BootstrapContext(samlToken, this);
            }

            return(identity);
        }
        /// <summary>
        /// Create claims from the token.
        /// </summary>
        /// <param name="samlToken">The token to translate to claims.</param>
        /// <returns>An identity with the created claims.</returns>
        public new ClaimsIdentity CreateClaims(Saml2SecurityToken samlToken)
        {
            var identity = base.CreateClaims(samlToken);

            if (Configuration.SaveBootstrapContext)
            {
                identity.BootstrapContext = new BootstrapContext(samlToken, this);
            }

            return identity;
        }
Exemple #17
0
        public void CompareSaml2SecurityTokens()
        {
            TestUtilities.WriteHeader($"{this}.CompareSaml2SecurityTokens", true);
            var context             = new CompareContext($"{this}.CompareSaml2SecurityTokens");
            var saml2SecurityToken1 = new Saml2SecurityToken(new Saml2Assertion(new Saml2NameIdentifier(Guid.NewGuid().ToString())));
            var saml2SecurityToken2 = new Saml2SecurityToken(new Saml2Assertion(new Saml2NameIdentifier(Guid.NewGuid().ToString())));

            IdentityComparer.AreEqual(saml2SecurityToken1, saml2SecurityToken2, context);
            Assert.True(context.Diffs.Count(s => s == "Id:") == 2);
            Assert.True(context.Diffs.Count(s => s == "Issuer:") == 2);
        }
Exemple #18
0
            public ITokenVisualizer GetTokenVisualizer(SecurityToken token)
            {
                Saml2SecurityToken saml2SecurityToken = token as Saml2SecurityToken;

                if (saml2SecurityToken == null)
                {
                    throw new ArgumentException("Token is not a SamlSecurityToken.");
                }

                return(new Saml2TokenVisualizer(saml2SecurityToken));
            }
Exemple #19
0
        /// <summary>
        /// Issuer URL should be a perfect match including case with the IDP
        /// </summary>
        /// <param name="assertion"></param>
        protected void ValidateIssuer(Saml2SecurityToken assertion)
        {
            if (_config.ValidIssuers.Count() > 0)
            {
                string issuer = GetIssuer(assertion);

                if (!_config.ValidIssuers.Any(m => m == issuer))
                {
                    throw new Exception("Issuer is not matching with the provided valid issuers.");
                }
            }
        }
        public string ToXml(Saml2Assertion assertion)
        {
            var tokenHandlers = new Saml2SecurityTokenHandler();
            var stringBuilder = new StringBuilder();
            using (var xmlWriter = new XmlTextWriter(new StringWriter(stringBuilder)))
            {
                var token = new Saml2SecurityToken(assertion);
                tokenHandlers.WriteToken(xmlWriter, token);

                return stringBuilder.ToString();
            }
        }
Exemple #21
0
        private GenericXmlSecurityToken SetSecurityToken <T>(T contract, Saml2SecurityToken samlToken,
                                                             CustomSaml2SecurityTokenHandler tokenHandler, SecurityTokenDescriptor tokenDescriptor)
            where T : SamlTokenContract
        {
            GenericXmlSecurityToken xmlToken;
            var outputTokenString   = samlToken.ToTokenXmlString();
            var attachedReference   = tokenHandler.CreateSecurityTokenReference(samlToken, true);
            var unattachedReference = tokenHandler.CreateSecurityTokenReference(samlToken, false);

            if (contract.Confirmation == SubjectConfirmationMethod.HolderOfKey)
            {
                if (contract is AsymmetricSamlTokenContract)
                {
                    xmlToken = new GenericXmlSecurityToken(
                        GetElement(outputTokenString),
                        new X509SecurityToken(contract.SigningCertificate),
                        DateTime.UtcNow,
                        DateTime.UtcNow.AddHours(8),
                        attachedReference,
                        unattachedReference,
                        new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>()));
                }
                else if (contract is SymmetricSamlTokenContract)
                {
                    var proof = (SymmetricProofDescriptor)tokenDescriptor.Proof;
                    xmlToken = new GenericXmlSecurityToken(
                        GetElement(outputTokenString),
                        new BinarySecretSecurityToken(proof.GetKeyBytes()),
                        DateTime.UtcNow,
                        DateTime.UtcNow.AddHours(8),
                        attachedReference,
                        unattachedReference,
                        new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>()));
                }
                else
                {
                    throw new InvalidOperationException("Unsupported Holder-of-Key contract: " + contract.GetType().Name);
                }
            }
            else
            {
                xmlToken = new GenericXmlSecurityToken(
                    GetElement(outputTokenString),
                    null,
                    DateTime.UtcNow,
                    DateTime.UtcNow.AddHours(8),
                    attachedReference,
                    unattachedReference,
                    new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>()));
            }
            return(xmlToken);
        }
Exemple #22
0
        public static string CallCreate(ChannelFactory <Resource> resourceFactory, Uri thisUrl, string smlDomain, int assuranceLevel, CreateRequest request, IMessageMetadata messageMetadata)
        {
            STARTLibrary.accesspointService.Resource ws = null;

            try
            {
                var serviceMetadata = !string.IsNullOrEmpty(smlDomain) ?
                                      ServiceMetadata.FromSml(smlDomain, request) :
                                      ServiceMetadata.FromKnownEndpoint(resourceFactory);

                //NOTE: if you want to debug and send to "wrong" address, change below:
                //var test1 = ServiceMetadata.FromSml(smlDomain, request); //henter metadata fra SML
                //var test2 = ServiceMetadata.FromKnownEndpoint(resourceFactory);
                //var test3 = new ServiceMetadata()
                //    {
                //        Address = new Uri("https://ehf.fylkesmannen.no/oxalis"), //factory.Endpoint.Address.Uri,
                //        Certificate = resourceFactory.Credentials.ServiceCertificate.DefaultCertificate
                //    };
                //serviceMetadata = test1;

                if (serviceMetadata.Certificate == null)
                {
                    throw new ArgumentException("Certificate required (both for custom validation and for authenticationMode \"MutualCertificate\").");
                }

                SetExpectedServiceCertificate(resourceFactory, serviceMetadata.Certificate);

                X509Certificate2 clientCertificate = resourceFactory.Credentials.ClientCertificate.Certificate;

                Saml2SecurityToken token = AccessPointToken.ClaimsToSaml2SenderVouchesToken(
                    AccessPointToken.MakeClaims(request.SenderIdentifier.Value, assuranceLevel),
                    thisUrl.AbsoluteUri, clientCertificate);

                //NOTE: changed when upgrading to .NET 4.5:
                //ws = resourceFactory.CreateChannelWithIssuedToken(new EndpointAddress(thisUrl, resourceFactory.Endpoint.Address.Identity), token);
                ws = resourceFactory.CreateChannelWithIssuedToken(token, new EndpointAddress(thisUrl, resourceFactory.Endpoint.Address.Identity));

                var response = ws.Create(request);
                return("Document sent.");
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                if (ws is IDisposable)
                {
                    (ws as IDisposable).Dispose();
                }
            };
        }
Exemple #23
0
        private string GetTokenString(string organizationName, bool isServiceBusScope)
        {
            // Generate Saml assertions..
            string issuerName = DefaultIssuer;
            //string issuerName = "localhost";

            Saml2NameIdentifier saml2NameIdentifier = new Saml2NameIdentifier(issuerName);             // this is the issuer name.
            Saml2Assertion      saml2Assertion      = new Saml2Assertion(saml2NameIdentifier);

            Uri acsScope = new Uri(StsPath(solutionName, isServiceBusScope));

            saml2Assertion.Conditions = new Saml2Conditions();
            saml2Assertion.Conditions
            .AudienceRestrictions.Add(new Saml2AudienceRestriction(acsScope));           // this is the ACS uri.

            saml2Assertion.Conditions.NotOnOrAfter = DateTime.Now.AddDays(1);            // Should this be utc?
            saml2Assertion.Conditions.NotBefore    = DateTime.Now.AddHours(-1);          // should this be utc?

            string certName = "localhost";

            X509Certificate2 localCert = RetrieveCertificate(certName);

            if (!localCert.HasPrivateKey)
            {
                throw new ArgumentException("Cert should have private key.", "certificate");
            }

            saml2Assertion.SigningCredentials = new X509SigningCredentials(localCert);             // this cert should have the private keys.

            // Add claim assertions.
            saml2Assertion.Statements.Add(
                new Saml2AttributeStatement(
                    new Saml2Attribute(OrganizationClaimType, organizationName)));

            // the submitter should always be a bearer.
            saml2Assertion.Subject = new Saml2Subject(new Saml2SubjectConfirmation(Saml2Constants.ConfirmationMethods.Bearer));

            // Wrap it into a security token.
            SecurityTokenHandler tokenHandler  = new Saml2SecurityTokenHandler();
            SecurityToken        securityToken = new Saml2SecurityToken(saml2Assertion);

            // Serialize the security token.
            StringBuilder sb = new StringBuilder();

            using (XmlWriter writer = XmlTextWriter.Create(new StringWriter(sb, CultureInfo.InvariantCulture)))
            {
                tokenHandler.WriteToken(writer, securityToken);
                writer.Close();
            }

            return(sb.ToString());
        }
        protected override void ValidateSubject(Saml2SecurityToken samlToken, TokenValidationParameters validationParameters)
        {
            base.ValidateSubject(samlToken, validationParameters);

            if (!samlToken.Assertion.Subject.SubjectConfirmations.Any())
            {
                throw new Saml2ResponseFailedValidationException("No subject confirmation method found.");
            }

            if (!samlToken.Assertion.Subject.SubjectConfirmations.Any(sc => sc.Method == bearerUri))
            {
                throw new Saml2ResponseFailedValidationException("Only assertions with subject confirmation method \"bearer\" are supported.");
            }
        }
Exemple #25
0
        private static IList <Saml2Attribute> GetTokenAttributes(Saml2SecurityToken samlToken)
        {
            IList <Saml2Attribute> attributes = null;

            foreach (Saml2Statement statement in samlToken.Assertion.Statements)
            {
                if (statement.GetType() == typeof(Saml2AttributeStatement))
                {
                    attributes = ((Saml2AttributeStatement)statement).Attributes;
                }
            }

            return(attributes);
        }
        private static string GetSaml2TokenString(Saml2SecurityToken token)
        {
            XmlWriterSettings writerSettings = new XmlWriterSettings();
            StringBuilder     sb             = new StringBuilder();

            writerSettings.OmitXmlDeclaration = true;

            using (XmlWriter xw = XmlWriter.Create(sb, writerSettings))
            {
                new Saml2SecurityTokenHandler().WriteToken(xw, token);

                return(sb.ToString());
            }
        }
Exemple #27
0
        public static XmlElement SerialiseToken(Saml2SecurityToken token)
        {
            var handler = new Saml2SecurityTokenHandler();
            var sb      = new StringBuilder();

            using (var writer = XmlWriter.Create(sb))
            {
                handler.WriteToken(writer, token);
                writer.Flush();
                var document = new XmlDocument();
                document.LoadXml(sb.ToString());
                return(document.DocumentElement);
            }
        }
Exemple #28
0
        /// <summary>
        /// Multiple audience can be validated. Check at least one audiance urls exist then allow passage.
        /// </summary>
        /// <param name="assertion"></param>
        protected void ValidateAudiance(Saml2SecurityToken assertion)
        {
            if (String.IsNullOrEmpty(_config.Audience))
            {
                throw new Exception("Missing Audience, specify the Audience URL.");
            }

            Uri audienceUri = new Uri(_config.Audience);

            if (!assertion.Assertion.Conditions.AudienceRestrictions.Any(m => m.Audiences.Any(o => o == audienceUri)))
            {
                throw new Exception("Issuer is not matching with the provided valid audiences.");
            }
        }
Exemple #29
0
        /// <summary>
        ///  Current time should be LESS THAN TimeStamp NotOnOrAfter UTC
        ///  Current time should be MORE THAN TimeStamp NotBefore UTC
        /// </summary>
        /// <param name="assertion"></param>
        protected void ValidateTimeStamp(Saml2SecurityToken assertion)
        {
            DateTime notOnOrAfter = assertion.Assertion.Conditions.NotOnOrAfter.Value;
            DateTime notBefore    = assertion.Assertion.Conditions.NotBefore.Value;

            if (DateTime.UtcNow >= notOnOrAfter)
            {
                throw new Exception("Current time should be LESS THAN TimeStamp NotOnOrAfter UTC");
            }

            if (DateTime.UtcNow <= notBefore)
            {
                throw new Exception("Current time should be MORE THAN TimeStamp NotBefore UTC");
            }
        }
Exemple #30
0
        private AccessTokenType?DetermineAccessTokenType(Saml2SecurityToken securityToken)
        {
            var method = securityToken.Assertion.Subject.SubjectConfirmations.FirstOrDefault()?.Method;

            if (method == Saml2BearerMethod)
            {
                return(AccessTokenType.Bearer);
            }

            if (method == Saml2HolderOfKeyMethod)
            {
                return(AccessTokenType.HolderOfKey);
            }

            return(null);
        }
        public void Validate(Saml2SecurityToken token, SecurityTokenHandlerConfiguration configuration)
        {
            if (token == null || token.Response == null || configuration == null)
            {
                throw new ArgumentNullException();
            }

            if (
                token.Response.Status != null &&
                token.Response.Status.StatusCode != null
                )
            {
                if (token.Response.Status.StatusCode.Value != StatusCodes.SUCCESS)
                {
                    throw new ValidationException(string.Format("Token status code validation error. Error reason: {0}", token.Response.Status.StatusCode.Value));
                }
            }
        }
Exemple #32
0
        protected void Page_Load(object sender, EventArgs e)
        {
            EnsureChildControls();

            //The email and given name values should be based on data from SQL User Store
            Dictionary <string, string> claims = new Dictionary <string, string>();

            claims[ClaimTypes.Name]      = User.Identity.Name;
            claims[ClaimTypes.Email]     = User.Identity.Name;
            claims[ClaimTypes.GivenName] = User.Identity.Name;

            Saml2SecurityToken token = SAMLFactory.CreateSaml2Token(
                ConfigurationManager.AppSettings["samlIssuedBy"],
                //This should be the username or user display name.  It will be modified by the relying system
                User.Identity.Name,
                claims,
                ConfigurationManager.AppSettings["x509CertThumbPrint"]);

            Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler();

            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding = System.Text.Encoding.UTF8;

            using (MemoryStream ms = new MemoryStream())
            {
                using (XmlWriter w = XmlWriter.Create(ms, xmlSettings))
                {
                    tokenHandler.WriteToken(w, token);
                    w.Flush();
                    w.Close();
                }
                ms.Position       = 0;
                samlresponse.Text = Convert.ToBase64String(ms.GetBuffer());
            }
            relaystate.Text = Page.Request.QueryString["RelayState"];

            HtmlGenericControl f = Page.FindControl("bodySSO") as HtmlGenericControl;

            if (f != null)
            {
                f.Attributes.Add("onload", "document.forms.form1.submit();");
            }
        }
Exemple #33
0
        private static List<SamlAttribute> GetClaims(Saml2SecurityToken samlToken)
        {
            IList<Saml2Attribute> attributes = GetTokenAttributes(samlToken);
            if (attributes == null)
                return null;

            var claims = new List<SamlAttribute>();
            foreach (Saml2Attribute attribute in attributes)
            {
                claims.AddRange(
                    SamlAttribute.SamlAttributeFromToken(attribute));
            }

            return claims;
        }
 public ClaimsIdentity CreateClaimsPublic(Saml2SecurityToken samlToken, string issuer, TokenValidationParameters validationParameters)
 {
     return base.CreateClaimsIdentity(samlToken, issuer, validationParameters);
 }
        void SerializeTokenToStream(Saml2SecurityToken saml2Token, CustomTextTraceSource ts, string section)
        {
            // serialize the token
            ts.TraceInformation(section);

            if (saml2Token.Assertion.Issuer != null)
            {
                ts.TraceInformation("\tIssuer: " + saml2Token.Assertion.Issuer.Value);
            }
            else
            {
                ts.TraceInformation("Saml 2 Assertion Issuer: NULL");
            }

            if (saml2Token.Assertion.Issuer != null)
            {
                ts.TraceInformation("\tSigningCredentials: " + saml2Token.Assertion.SigningCredentials.ToString());
            }
            else
            {
                ts.TraceInformation("Saml 2 Assertion SigningCredentials: NULL");
            }

            if (saml2Token.Assertion.Subject != null)
            {
                if (saml2Token.Assertion.Subject.NameId != null)
                {
                    ts.TraceInformation("\tSubject NameId: " + saml2Token.Assertion.Subject.NameId.Value);
                }
                else
                {
                    ts.TraceInformation("\tSubject NameId: NULL");
                }
            }
            else
            {
                ts.TraceInformation("Saml 2 Assertion Subject: NULL");
            }

            ts.TraceInformation("Saml Token:\n");

            ts.TraceInformation(TokenToString(saml2Token));

        }
        // Pass thru the claims of the original user
        protected override IClaimsIdentity CreateClaims(Saml2SecurityToken samlToken)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.CreateClaims",
                "MyTraceSource", SourceLevels.Information);

            // process subject in base 
            IClaimsIdentity subject = base.CreateClaims(samlToken);

            Saml2Assertion assertion = samlToken.Assertion;

            // process Condition/Delegation 
           
            // TODO: Refactor to a function ProcessDelegation()
            ts.TraceInformation("assertion.Conditions Type: " + assertion.Conditions.GetType().Name);

            if (assertion.Conditions is Saml2ConditionsDelegateWrapper)
            {
                Saml2ConditionsDelegateWrapper delegateData = assertion.Conditions as Saml2ConditionsDelegateWrapper;

                // Iterate over the Condition delegate elements
                // Check if there are delegates within an incoming assertion
                IClaimsIdentity currentSubject = subject;

                if (delegateData != null && delegateData.Delegates != null)
                {
                    // Add the delegates in the DelegationRestrictionType
                    ts.TraceInformation("Number of Delegates: " + delegateData.Delegates.Delegate.Length);
                    for (int i = 0; i < delegateData.Delegates.Delegate.Length; i++)
                    {
                        DelegateType del = delegateData.Delegates.Delegate[i];

                        if (del != null)
                        {
                            string nameId = del.Item.ToString();

                            var claims = new List<Claim>();
                            claims.Add(new Claim(ClaimTypes.Name, nameId));
                            claims.Add(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(del.DelegationInstant, DateTimeFormats.Generated)));

                            // now add to current subject
                            currentSubject.Actor = new ClaimsIdentity(claims);

                            currentSubject = currentSubject.Actor;
                        }
                    }
                }
            }

            return subject;
        }
        /// <summary>
        /// Returns the time until which the token should be held in the token replay cache.
        /// </summary>
        /// <param name="token">The token to return an expiration time for.</param>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        /// <exception cref="SecurityTokenValidationException">The Saml2SecurityToken's validity period is greater than the expiration period set to TokenReplayCache.</exception>
        /// <returns>A DateTime representing the expiration time.</returns>
        /// <remarks>By default, this function returns the NotOnOrAfter of the SAML Condition if present.
        /// If that value does not exist, it returns the NotOnOrAfter of the first SubjectConfirmationData.
        /// This function will never return a value further from now than Configuration.TokenReplayCacheExpirationPeriod.</remarks>
        protected virtual DateTime GetTokenReplayCacheEntryExpirationTime(Saml2SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            DateTime? tokenExpiration = null;
            Saml2Assertion assertion = token.Assertion;
            if (assertion != null)
            {
                if (assertion.Conditions != null && assertion.Conditions.NotOnOrAfter.HasValue)
                {
                    // The Condition has a NotOnOrAfter set, use that.
                    tokenExpiration = assertion.Conditions.NotOnOrAfter.Value;
                }
                else if (assertion.Subject != null && assertion.Subject.SubjectConfirmations != null &&
                          assertion.Subject.SubjectConfirmations.Count != 0 &&
                          assertion.Subject.SubjectConfirmations[0].SubjectConfirmationData != null &&
                          assertion.Subject.SubjectConfirmations[0].SubjectConfirmationData.NotOnOrAfter.HasValue)
                {
                    // The condition did not have NotOnOrAfter set, but SCD[0] has a NotOnOrAfter set, use that.
                    tokenExpiration = assertion.Subject.SubjectConfirmations[0].SubjectConfirmationData.NotOnOrAfter.Value;
                }
            }

            // DateTimeUtil handles overflows
            DateTime maximumExpirationTime = DateTimeUtil.Add(DateTime.UtcNow, Configuration.TokenReplayCacheExpirationPeriod);

            // Use DateTime.MaxValue as expiration value for tokens without expiration
            tokenExpiration = tokenExpiration ?? DateTime.MaxValue;

            // If the refined token validity period is greater than the TokenReplayCacheExpirationPeriod, throw
            if (DateTime.Compare(maximumExpirationTime, tokenExpiration.Value) < 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new SecurityTokenValidationException(SR.GetString(SR.ID1069, tokenExpiration.Value.ToString(), Configuration.TokenReplayCacheExpirationPeriod.ToString())));
            }

            return tokenExpiration.Value;
        }
        /// <summary>
        /// Creates claims from a Saml2 token.
        /// </summary>
        /// <param name="samlToken">The Saml2SecurityToken.</param>
        /// <returns>An IClaimIdentity.</returns>
        protected virtual ClaimsIdentity CreateClaims(Saml2SecurityToken samlToken)
        {
            if (samlToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlToken");
            }

            ClaimsIdentity subject = new ClaimsIdentity(AuthenticationTypes.Federation, SamlSecurityTokenRequirement.NameClaimType, SamlSecurityTokenRequirement.RoleClaimType);

            Saml2Assertion assertion = samlToken.Assertion;

            if (assertion == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("samlToken", SR.GetString(SR.ID1034));
            }

            if (this.Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (this.Configuration.IssuerNameRegistry == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4277));
            }

            string issuer = this.Configuration.IssuerNameRegistry.GetIssuerName(samlToken.IssuerToken, assertion.Issuer.Value);

            if (string.IsNullOrEmpty(issuer))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4175)));
            }

            this.ProcessSamlSubject(assertion.Subject, subject, issuer);
            this.ProcessStatement(assertion.Statements, subject, issuer);

            return subject;
        }
        /// <summary>
        /// Creates a <see cref="SecurityToken"/> based on a information contained in the <see cref="SecurityTokenDescriptor"/>.
        /// </summary>
        /// <param name="tokenDescriptor">The <see cref="SecurityTokenDescriptor"/> that has creation information.</param>
        /// <returns>A <see cref="SecurityToken"/> instance.</returns>
        /// <exception cref="ArgumentNullException">Thrown if 'tokenDescriptor' is null.</exception>
        public override SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor)
        {
            if (null == tokenDescriptor)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }

            // Assertion/issuer
            Saml2Assertion assertion = new Saml2Assertion(this.CreateIssuerNameIdentifier(tokenDescriptor));

            // Subject
            assertion.Subject = this.CreateSamlSubject(tokenDescriptor);

            // Signature
            assertion.SigningCredentials = this.GetSigningCredentials(tokenDescriptor);

            // Conditions
            assertion.Conditions = this.CreateConditions(tokenDescriptor.Lifetime, tokenDescriptor.AppliesToAddress, tokenDescriptor);

            // Advice
            assertion.Advice = this.CreateAdvice(tokenDescriptor);

            // Statements
            IEnumerable<Saml2Statement> statements = this.CreateStatements(tokenDescriptor);
            if (null != statements)
            {
                foreach (Saml2Statement statement in statements)
                {
                    assertion.Statements.Add(statement);
                }
            }

            // encrypting credentials
            assertion.EncryptingCredentials = this.GetEncryptingCredentials(tokenDescriptor);

            SecurityToken token = new Saml2SecurityToken(assertion);

            return token;
        }
 public Saml2TokenVisualizer(Saml2SecurityToken token)
 {
     this.Token = token;
 }
 public new ClaimsIdentity CreateClaims(Saml2SecurityToken samlToken)
 {
     return base.CreateClaims(samlToken);
 }
        public void Saml2Response_GetClaims_CorrectEncryptedSingleAssertion_UsingWIF()
        {
            var response =
            @"<saml2p:Response xmlns:saml2p=""urn:oasis:names:tc:SAML:2.0:protocol""
            xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion""
            ID = """ + MethodBase.GetCurrentMethod().Name + @""" Version=""2.0"" IssueInstant=""2013-01-01T00:00:00Z"">
                <saml2:Issuer>https://idp.example.com</saml2:Issuer>
                <saml2p:Status>
                    <saml2p:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" />
                </saml2p:Status>
                {0}
            </saml2p:Response>";

            var assertion = new Saml2Assertion(new Saml2NameIdentifier("https://idp.example.com"));
            assertion.Subject = new Saml2Subject(new Saml2NameIdentifier("WIFUser"));
            assertion.Subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer")));
            assertion.Conditions = new Saml2Conditions { NotOnOrAfter = new DateTime(2100, 1, 1) };

            var token = new Saml2SecurityToken(assertion);
            var handler = new Saml2SecurityTokenHandler();

            assertion.SigningCredentials = new X509SigningCredentials(SignedXmlHelper.TestCert,
                signatureAlgorithm: SecurityAlgorithms.RsaSha1Signature,
                digestAlgorithm: SecurityAlgorithms.Sha1Digest);

            assertion.EncryptingCredentials = new EncryptedKeyEncryptingCredentials(
                SignedXmlHelper.TestCert2,
                keyWrappingAlgorithm: SecurityAlgorithms.RsaOaepKeyWrap,
                keySizeInBits: 256,
                encryptionAlgorithm: SecurityAlgorithms.Aes192Encryption);

            string assertionXml = String.Empty;
            using (var sw = new StringWriter())
            {
                using (var xw = XmlWriter.Create(sw, new XmlWriterSettings { OmitXmlDeclaration = true }))
                {
                    handler.WriteToken(xw, token);
                }
                assertionXml = sw.ToString();
            }
            var responseWithAssertion = string.Format(response, assertionXml);

            var claims = Saml2Response.Read(responseWithAssertion).GetClaims(Options.FromConfiguration);
            claims.Count().Should().Be(1);
            claims.First().FindFirst(ClaimTypes.NameIdentifier).Value.Should().Be("WIFUser");
        }
 protected override ClaimsIdentity CreateClaims(Saml2SecurityToken samlToken)
 {
     Console.WriteLine(samlToken.Id);
     return base.CreateClaims(samlToken);
 }
        /// <summary>
        /// Creates a <see cref="ClaimsIdentity"/> from the Saml2 securityToken.
        /// </summary>
        /// <param name="samlToken">The Saml2SecurityToken.</param>
        /// <param name="issuer">the issuer value for each <see cref="Claim"/> in the <see cref="ClaimsIdentity"/>.</param>
        /// <param name="validationParameters"> contains parameters for validating the securityToken.</param>
        /// <returns>An IClaimIdentity.</returns>
        protected virtual ClaimsIdentity CreateClaimsIdentity(Saml2SecurityToken samlToken, string issuer, TokenValidationParameters validationParameters)
        {
            if (samlToken == null)
            {
                throw new ArgumentNullException("samlToken");
            }

            if (string.IsNullOrWhiteSpace(issuer))
            {
                throw new ArgumentException(ErrorMessages.IDX10221);
            }

            Saml2Assertion assertion = samlToken.Assertion;
            if (assertion == null)
            {
                throw new ArgumentException(ErrorMessages.IDX10202);
            }

            ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(samlToken, issuer);
            _smSaml2HandlerPrivateNeverSetAnyProperties.ProcessSamlSubjectPublic(samlToken.Assertion.Subject, identity, issuer);
            _smSaml2HandlerPrivateNeverSetAnyProperties.ProcessStatmentPublic(samlToken.Assertion.Statements, identity, issuer);
            return identity;
        }
Exemple #45
0
        private static IList<Saml2Attribute> GetTokenAttributes(Saml2SecurityToken samlToken)
        {
            IList<Saml2Attribute> attributes = null;
            foreach (Saml2Statement statement in samlToken.Assertion.Statements)
                if (statement.GetType() == typeof(Saml2AttributeStatement))
                    attributes = ((Saml2AttributeStatement)statement).Attributes;

            return attributes;
        }