Ejemplo n.º 1
0
		public void MatchesKeyIdentifierClause ()
		{
			UniqueId id = new UniqueId ();
			X509SecurityToken t = new X509SecurityToken (cert, id.ToString ());
			LocalIdKeyIdentifierClause l =
				new LocalIdKeyIdentifierClause (id.ToString ());
			Assert.IsTrue (t.MatchesKeyIdentifierClause (l), "#1-1");

			l = new LocalIdKeyIdentifierClause ("#" + id.ToString ());
			Assert.IsFalse (t.MatchesKeyIdentifierClause (l), "#1-2");

			X509ThumbprintKeyIdentifierClause h =
				new X509ThumbprintKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (h), "#2-1");

			h = new X509ThumbprintKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (h), "#2-2");

			X509IssuerSerialKeyIdentifierClause i =
				new X509IssuerSerialKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (i), "#3-1");

			i = new X509IssuerSerialKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (i), "#3-2");

			X509RawDataKeyIdentifierClause s =
				new X509RawDataKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (s), "#4-1");

			s = new X509RawDataKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (s), "#4-2");
		}
Ejemplo n.º 2
0
        /// <summary>
        /// Build a new RequestSecurityToken structure without actually sending it.
        /// </summary>
        /// <param name="bootstrapSecurityToken">The token to include in ActAs</param>
        /// <param name="clientCertificate">The instance certificate. Must have a private key.</param>
        /// <param name="RelyingPartyAdress">Address/uri of the provider service which is going to receive the token in the end</param>
        /// <param name="requestClaims">Any additional claims to add to the request</param>
        /// <returns></returns>
        public static RequestSecurityToken RequestSecurityToken(SecurityToken bootstrapSecurityToken, X509Certificate2 clientCertificate, Uri RelyingPartyAdress, IEnumerable<RequestClaim> requestClaims)
        {
            var requestSecurityToken = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
            requestSecurityToken.AppliesTo = new EndpointAddress(RelyingPartyAdress);
            requestSecurityToken.TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
            requestSecurityToken.KeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
            requestSecurityToken.ActAs = new SecurityTokenElement(bootstrapSecurityToken);
            SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(clientCertificate);
            requestSecurityToken.UseKey = new UseKey(new SecurityKeyIdentifier(clause), new X509SecurityToken(clientCertificate));

            foreach (RequestClaim claim in requestClaims)
            {
                requestSecurityToken.Claims.Add(claim);
            }

            return requestSecurityToken;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Generate a sample MetadataBase.
        /// </summary>
        /// <remarks>
        /// In a production system this would be generated from the STS configuration.
        /// </remarks>
        public static MetadataBase GetFederationMetadata()
        {
            string endpointId = "http://localhost:61754/";
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(endpointId);

            // Define the signing key
            string signingCertificateName = WebConfigurationManager.AppSettings["SigningCertificateName"];
            X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateName);
            metadata.SigningCredentials = new X509SigningCredentials(cert);

            // Create role descriptor for security token service
            SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();
            stsRole.ProtocolsSupported.Add(new Uri(WSFederationMetadataConstants.Namespace));
            metadata.RoleDescriptors.Add(stsRole);

            // Add a contact name
            ContactPerson person = new ContactPerson(ContactType.Administrative);
            person.GivenName = "contactName";
            stsRole.Contacts.Add(person);

            // Include key identifier for signing key in metadata
            SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(cert);
            SecurityKeyIdentifier ski = new SecurityKeyIdentifier(clause);
            KeyDescriptor signingKey = new KeyDescriptor(ski);
            signingKey.Use = KeyType.Signing;
            stsRole.Keys.Add(signingKey);

            // Add endpoints
            string activeSTSUrl = "http://localhost:61754/";
            EndpointAddress endpointAddress = new EndpointAddress(new Uri(activeSTSUrl),
                                                                   null,
                                                                   null, GetMetadataReader(activeSTSUrl), null);
            stsRole.SecurityTokenServiceEndpoints.Add(endpointAddress);

            // Add a collection of offered claims
            // NOTE: In this sample, these claims must match the claims actually generated in CustomSecurityTokenService.GetOutputClaimsIdentity.
            //       In a production system, there would be some common data store that both use
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "The name of the subject."));
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "The role of the subject."));
            // Add a special claim for the QuoteService
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(QuotationClassClaimType, "QuotationClass", "Class of quotation desired."));

            return metadata;
        }
        public ActionResult FederationMetadata()
        {
            var endpoint = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port;
            var entityDescriptor = new EntityDescriptor(new EntityId(ConfigurationManager.AppSettings["stsName"]))
                                   {
                                       SigningCredentials = CertificateFactory.GetSigningCredentials()
                                   };

            var roleDescriptor = new SecurityTokenServiceDescriptor();
            roleDescriptor.Contacts.Add(new ContactPerson(ContactType.Administrative));

            var clause = new X509RawDataKeyIdentifierClause(CertificateFactory.GetCertificate());
            var securityKeyIdentifier = new SecurityKeyIdentifier(clause);
            var signingKey = new KeyDescriptor(securityKeyIdentifier) {Use = KeyType.Signing};
            roleDescriptor.Keys.Add(signingKey);

            var endpointAddress =
                new System.IdentityModel.Protocols.WSTrust.EndpointReference(endpoint + "/Security/Authorize");

            roleDescriptor.PassiveRequestorEndpoints.Add(endpointAddress);
            roleDescriptor.SecurityTokenServiceEndpoints.Add(endpointAddress);

            roleDescriptor.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            entityDescriptor.RoleDescriptors.Add(roleDescriptor);

            var serializer = new MetadataSerializer();
            var settings = new XmlWriterSettings {Encoding = Encoding.UTF8};

            var memoryStream = new MemoryStream();
            var writer = XmlWriter.Create(memoryStream, settings);
            serializer.WriteMetadata(writer,entityDescriptor);
            writer.Flush();

            var content = Content(Encoding.UTF8.GetString(memoryStream.GetBuffer()), "text/xml");
            writer.Dispose();

            return content;
        }
Ejemplo n.º 5
0
        private static SecurityKeyIdentifierClause ReadX509Certificate(XmlReader reader)
        {
            reader.ReadStartElement("X509Certificate", SignedXml.XmlDsigNamespaceUrl);
            var clause = new X509RawDataKeyIdentifierClause(
                ((XmlDictionaryReader)reader).ReadContentAsBase64());
            reader.ReadEndElement();

            return clause;
        }
Ejemplo n.º 6
0
            public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore( XmlDictionaryReader reader )
            {
                SecurityKeyIdentifierClause ski = null;
                reader.ReadStartElement( XD.XmlSignatureDictionary.X509Data, NamespaceUri );
                while ( reader.IsStartElement() )
                {
                    if ( ski == null && reader.IsStartElement( XD.XmlSignatureDictionary.X509Certificate, NamespaceUri ) )
                    {
                        X509Certificate2 certificate = null;
                        if ( !SecurityUtils.TryCreateX509CertificateFromRawData( reader.ReadElementContentAsBase64(), out certificate ) )
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityMessageSerializationException( SR.GetString( SR.InvalidX509RawData ) ) );
                        }
                        ski = new X509RawDataKeyIdentifierClause( certificate );
                    }
                    else if ( ski == null && reader.IsStartElement( XmlSignatureStrings.X509Ski, NamespaceUri.ToString() ) )
                    {
                        ski = new X509SubjectKeyIdentifierClause( reader.ReadElementContentAsBase64() );
                    }
                    else if ( ( ski == null ) && reader.IsStartElement( XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace ) )
                    {
                        reader.ReadStartElement( XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace );
                        reader.ReadStartElement( XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace );
                        string issuerName = reader.ReadContentAsString();
                        reader.ReadEndElement();
                        reader.ReadStartElement( XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace );
                        string serialNumber = reader.ReadContentAsString();
                        reader.ReadEndElement();
                        reader.ReadEndElement();

                        ski = new X509IssuerSerialKeyIdentifierClause( issuerName, serialNumber );
                    }
                    else
                    {
                        reader.Skip();
                    }
                }
                reader.ReadEndElement();
                return ski;
            }
Ejemplo n.º 7
0
        static ClaimsPrincipal ValidateTokenWithX509SecurityToken(X509RawDataKeyIdentifierClause x509DataClause, string token)
        {
            var validatingCertificate = new X509Certificate2(x509DataClause.GetX509RawData());
            var tokenHandler = new JwtSecurityTokenHandler();
            var x509SecurityToken = new X509SecurityToken(validatingCertificate);
            var validationParameters = new TokenValidationParameters()
            {
                AllowedAudience = "http://www.example.com",
                SigningToken = x509SecurityToken,
                ValidIssuer = "self",
            };

            ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(new JwtSecurityToken(token), validationParameters);
            return claimsPrincipal;
        }