public static ClaimsIdentity CreateIdentityFromToken(this string token, X509Certificate2 certificate = null) { if (token == null) { throw new ArgumentNullException("token"); } var tokenHandler = new JwtSecurityTokenHandler(); if (certificate != null) { var x509SecurityToken = new X509SecurityToken(certificate); var validationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() { ValidAudience = Audience, IssuerSigningToken = x509SecurityToken, ValidIssuer = Issuer, }; System.IdentityModel.Tokens.SecurityToken validatedToken; var claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken); return(claimsPrincipal.Identity as ClaimsIdentity); } var jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token); return(new ClaimsIdentity(jwtToken.Claims, Issuer, JwtRegisteredClaimNames.UniqueName, CustomClaimTypes.Task)); }
public ReadyStatus Ready() { // Dump HTTP reqquest System.Web.HttpContext cntx = this.Context; cntx.Request.SaveAs(Server.MapPath("httpdump.txt"), true); // Verifies that a SOAP request was received. SoapContext requestContext = HttpSoapContext.RequestContext; if (requestContext == null) { throw new ApplicationException("Either a non-SOAP request was " + "received or the WSE is not properly installed for " + "the Web application hosting the XML Web service."); } X509SecurityToken theToken = GetFirstX509Token(requestContext.Security); ReadyStatus r = new ReadyStatus(); r.Status = ReadyCode.Ready; r.Description = DescribeReadyCode(r.Status); return(r); }
// Requires Nuget-package System.IdentityModel.Tokens.Jwt private TokenValidationParameters CreateTokenValidationParameters() { //Can be retrieved dynamically x5c from /core/.well-known/jwks // Depending on performance, we may want to put the x5c value in config versus making a call to get it // every single time a wcf service call is made. HttpClient _client = new HttpClient(); // Get Json Web Key from Identity Server string _jwks = _client.GetStringAsync(string.Format("{0}/core/.well-known/jwks", _identityServerUrl)).Result; // Parse as Json Object so it can be read JObject _jObject = JObject.Parse(_jwks); // The return value is a keys array with one element var _x5cArray = _jObject["keys"][0]["x5c"]; // For some reason, the xc5 is stored as an array so the first element must be used to get the xc5 value // from the certificate string _x5c = (string)_x5cArray[0]; var rawData = Encoding.UTF8.GetBytes(_x5c); var x509Certificate2 = new X509Certificate2(rawData); var x509SecurityToken = new X509SecurityToken(x509Certificate2); var parameters = new TokenValidationParameters { ValidAudience = string.Format("{0}/resources", _identityServerUrl), ValidIssuer = _identityServerUrl, IssuerSigningToken = x509SecurityToken }; return(parameters); }
/// <summary> /// Gets the name of the issuer. /// </summary> /// <param name="securityToken">The security token.</param> /// <returns></returns> public override string GetIssuerName(SecurityToken securityToken) { if (securityToken == null) { Tracing.Error("SimpleIssuerNameRegistry: securityToken is null"); throw new ArgumentNullException("securityToken"); } X509SecurityToken token = securityToken as X509SecurityToken; if (token != null) { Tracing.Information("SimpleIssuerNameRegistry: X509 SubjectName: " + token.Certificate.SubjectName.Name); Tracing.Information("SimpleIssuerNameRegistry: X509 Thumbprint : " + token.Certificate.Thumbprint); return(token.Certificate.Thumbprint); } RsaSecurityToken token2 = securityToken as RsaSecurityToken; if (token2 == null) { throw new SecurityTokenException(securityToken.GetType().FullName); } Tracing.Information("SimpleIssuerNameRegistry: RSA Key: " + token2.Rsa.ToXmlString(false)); return(token2.Rsa.ToXmlString(false)); }
private void CallWebService(int a, int b, string url) { // Instantiate an instance of the web service proxy AddNumbers serviceProxy = new AddNumbers(); SoapContext requestContext = serviceProxy.RequestSoapContext; // Get the Asymmetric key X509SecurityToken token = GetEncryptionToken(); if (token == null) { throw new ApplicationException("No security token provided."); } // Add an EncryptedData element to the security collection // to encrypt the request. requestContext.Security.Elements.Add(new EncryptedData(token)); if (url != null) { serviceProxy.Url = url; } // Call the service Console.WriteLine("Calling {0}", serviceProxy.Url); int sum = serviceProxy.AddInt(a, b); // Success! string message = string.Format("{0} + {1} = {2}", a, b, sum); Console.WriteLine("Web Service returned: {0}", message); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { userToken = new UsernameToken(parentAssertion.Username.Trim(), parentAssertion.Password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken(); sig = new MessageSignature(signatureToken); }
public string DescribeReadyCode(ReadyCode code) { // Dump HTTP reqquest System.Web.HttpContext cntx = this.Context; cntx.Request.SaveAs(Server.MapPath("httpdump.txt"), true); // Verifies that a SOAP request was received. SoapContext requestContext = HttpSoapContext.RequestContext; if (requestContext == null) { throw new ApplicationException("Either a non-SOAP request was " + "received or the WSE is not properly installed for " + "the Web application hosting the XML Web service."); } X509SecurityToken theToken = GetFirstX509Token(requestContext.Security); switch (code) { case ReadyCode.Ready: return("Systemet er klar til at modtage indberetningsklienten."); case ReadyCode.Error_CertificateExpired: return("Certifikatet er udløbet."); default: case ReadyCode.Error_Unknown: return("Ukendt fejl."); } }
private static X509SecurityToken RetrieveTokenFromStore(X509CertificateStore store, string keyIdentifier) { if (store == null) { throw new ArgumentNullException("store"); } X509SecurityToken token = null; try { if (store.OpenRead()) { // Place the key ID of the certificate in a byte array // This KeyID represents the Wse2Quickstart certificate included with the WSE 2.0 Quickstarts // ClientBase64KeyId is defined in the ClientBase.AppBase class X509CertificateCollection certs = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(keyIdentifier)); if (certs.Count > 0) { // Get the first certificate in the collection token = new X509SecurityToken(((X509Certificate)certs[0])); } } } finally { if (store != null) { store.Close(); } } return(token); }
private bool TryResolveTokenFromIntrinsicKeyClause(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token) { token = null; if (keyIdentifierClause is RsaKeyIdentifierClause) { token = new RsaSecurityToken(((RsaKeyIdentifierClause)keyIdentifierClause).Rsa); return(true); } if (keyIdentifierClause is X509RawDataKeyIdentifierClause) { token = new X509SecurityToken(new X509Certificate2(((X509RawDataKeyIdentifierClause)keyIdentifierClause).GetX509RawData()), false); return(true); } if (keyIdentifierClause is EncryptedKeyIdentifierClause) { SecurityToken token2; EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause; SecurityKeyIdentifier encryptingKeyIdentifier = keyClause.EncryptingKeyIdentifier; if (base.TryResolveToken(encryptingKeyIdentifier, out token2)) { token = System.ServiceModel.Security.SecurityUtils.CreateTokenFromEncryptedKeyClause(keyClause, token2); return(true); } } return(false); }
// callback from schannel private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (_parent.RequireClientCertificate) { if (certificate == null) { Contract.Assert(certificate != null, "certificate MUST NOT be null"); return(false); } // Note: add ref to handle since the caller will reset the cert after the callback return. X509Certificate2 certificate2 = new X509Certificate2(certificate.Handle); _clientCertificate = certificate2; try { SecurityToken token = new X509SecurityToken(certificate2, false); ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = _parent.ClientCertificateAuthenticator.ValidateToken(token); _clientSecurity = new SecurityMessageProperty(); _clientSecurity.TransportToken = new SecurityTokenSpecification(token, authorizationPolicies); _clientSecurity.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); } catch (SecurityTokenException) { return(false); } } return(true); }
private static SigningCredentials SetSigningCredentials <T>(T contract) where T : SamlTokenContract { SigningCredentials signingCredentials; if (contract.UseRsa) { var rsa = contract.SigningCertificate.PrivateKey as RSACryptoServiceProvider; if (rsa == null) { throw new InvalidOperationException( "Signing certificate must include private key for RSA signature."); } var rsaKey = new RsaSecurityKey(rsa); var rsaClause = new RsaKeyIdentifierClause(rsa); var ski = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { rsaClause }); signingCredentials = new SigningCredentials(rsaKey, contract.AlgorithmSuite.DefaultAsymmetricSignatureAlgorithm, contract.AlgorithmSuite.DefaultDigestAlgorithm, ski); } else { var clause = new X509SecurityToken(contract.SigningCertificate) .CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>(); var ski = new SecurityKeyIdentifier(clause); signingCredentials = new X509SigningCredentials(contract.SigningCertificate, ski, contract.AlgorithmSuite.DefaultAsymmetricSignatureAlgorithm, contract.AlgorithmSuite.DefaultDigestAlgorithm); } return(signingCredentials); }
void Context_PostAuthenticateRequest(object sender, EventArgs e) { var context = ((HttpApplication)sender).Context; // no need to call transformation if session already exists if (FederatedAuthentication.SessionAuthenticationModule != null && FederatedAuthentication.SessionAuthenticationModule.ContainsSessionTokenCookie(context.Request.Cookies)) { return; } var transformer = FederatedAuthentication.ServiceConfiguration.ClaimsAuthenticationManager; if (transformer != null) { var principal = context.User as ClaimsPrincipal; if (context.Request.ClientCertificate.IsPresent && context.Request.ClientCertificate.IsValid) { var cert = new X509Certificate2(context.Request.ClientCertificate.Certificate); var token = new X509SecurityToken(cert); var certId = new HttpsSecurityTokenHandler().ValidateToken(token).First(); principal.Identities.Add(certId); } var transformedPrincipal = transformer.Authenticate(context.Request.RawUrl, principal); context.User = transformedPrincipal; Thread.CurrentPrincipal = transformedPrincipal; } }
private static bool Matches(SecurityKeyIdentifierClause keyIdentifierClause, SecurityKey key, CertMatcher certMatcher, out SecurityToken token) { token = null; if (certMatcher != null) { X509SecurityKey x509Key = key as X509SecurityKey; if (x509Key != null) { if (certMatcher(x509Key.Certificate)) { token = new X509SecurityToken(x509Key.Certificate); return(true); } } else { X509AsymmetricSecurityKey x509AsymmKey = key as X509AsymmetricSecurityKey; if (x509AsymmKey != null) { X509Certificate2 cert = _certFieldInfo.GetValue(x509AsymmKey) as X509Certificate2; if (cert != null && certMatcher(cert)) { token = new X509SecurityToken(cert); return(true); } } } } return(false); }
private Saml2Assertion CreateSamlAssertionWithSymmetricKey(BinarySecretSecurityToken proofToken) { X509SecurityToken x509SecurityToken = new X509SecurityToken(base.ClientCredentials.ClientCertificate.Certificate); X509SecurityToken x509SecurityToken2 = new X509SecurityToken(base.ClientCredentials.ServiceCertificate.DefaultCertificate); SecurityKey signatureKey = x509SecurityToken.SecurityKeys[0]; SecurityKeyIdentifierClause securityKeyIdentifierClause = x509SecurityToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>(); SecurityKeyIdentifier signatureKeyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { securityKeyIdentifierClause }); SecurityKey securityKey = x509SecurityToken2.SecurityKeys[0]; SecurityKeyIdentifierClause securityKeyIdentifierClause2 = x509SecurityToken2.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>(); SecurityKeyIdentifier encryptingKeyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { securityKeyIdentifierClause2 }); byte[] keyBytes = proofToken.GetKeyBytes(); byte[] encryptedKey = securityKey.EncryptKey(base.SecurityAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm, keyBytes); SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { new EncryptedKeyIdentifierClause(encryptedKey, base.SecurityAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm, encryptingKeyIdentifier) }); return(this.CreateSamlAssertion(signatureKey, signatureKeyIdentifier, proofKeyIdentifier)); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { userToken = new UsernameToken(parentAssertion.Username.Trim(), parentAssertion.Password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken(); sig = new MessageSignature(signatureToken); }
SspiNegotiationTokenProviderState CreateTlsSspiState(X509SecurityToken token) { X509Certificate2 clientCertificate; if (token == null) { clientCertificate = null; } else { clientCertificate = token.Certificate; } TlsSspiNegotiation tlsNegotiation = null; if (LocalAppContextSwitches.DisableUsingServicePointManagerSecurityProtocols) { tlsNegotiation = new TlsSspiNegotiation(String.Empty, SchProtocols.Ssl3Client | SchProtocols.TlsClient, clientCertificate); } else { var protocol = (SchProtocols)System.Net.ServicePointManager.SecurityProtocol & SchProtocols.ClientMask; tlsNegotiation = new TlsSspiNegotiation(String.Empty, protocol, clientCertificate); } return(new SspiNegotiationTokenProviderState(tlsNegotiation)); }
static void GetTokensCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } CreateSspiStateAsyncResult typedResult = (CreateSspiStateAsyncResult)result.AsyncState; try { SecurityToken token = typedResult.tlsTokenProvider.ClientTokenProvider.EndGetToken(result); X509SecurityToken clientToken = TlsnegoTokenProvider.ValidateToken(token); typedResult.sspiState = typedResult.tlsTokenProvider.CreateTlsSspiState(clientToken); typedResult.Complete(false); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } typedResult.Complete(false, e); } }
protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateSspiNegotiation(ISspiNegotiation sspiNegotiation) { TlsSspiNegotiation tlsNegotiation = (TlsSspiNegotiation)sspiNegotiation; if (tlsNegotiation.IsValidContext == false) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.InvalidSspiNegotiation))); } X509Certificate2 serverCert = tlsNegotiation.RemoteCertificate; if (serverCert == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.ServerCertificateNotProvided))); } ReadOnlyCollection <IAuthorizationPolicy> authzPolicies; if (this.ServerTokenAuthenticator != null) { X509SecurityToken certToken = new X509SecurityToken(serverCert, false); authzPolicies = this.ServerTokenAuthenticator.ValidateToken(certToken); } else { authzPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance; } return(authzPolicies); }
// callback from schannel bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (parent.RequireClientCertificate) { if (certificate == null) { return(false); } // Note: add ref to handle since the caller will reset the cert after the callback return. X509Certificate2 certificate2 = new X509Certificate2(certificate); clientCertificate = certificate2; try { SecurityToken token = new X509SecurityToken(certificate2, false); ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = parent.ClientCertificateAuthenticator.ValidateToken(token); clientSecurity = new SecurityMessageProperty(); clientSecurity.TransportToken = new SecurityTokenSpecification(token, authorizationPolicies); clientSecurity.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); } catch (SecurityTokenException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); return(false); } } return(true); }
public WsTrustClientMessageInspector(ClientCredentials clientCredentials) { // Reusing the WCF tokens as there is a built-in serializer for those. if (clientCredentials.ClientCertificate.Certificate != null) { string tokenId = CreateElementId(SECURITY_TOKEN_ID_PREFIX); _certificateToken = new X509SecurityToken( clientCredentials.ClientCertificate.Certificate, tokenId); } if (clientCredentials.UserName.UserName != null) { string tokenId = CreateElementId(SECURITY_TOKEN_ID_PREFIX); _userNameToken = new UserNameSecurityToken( clientCredentials.UserName.UserName, clientCredentials.UserName.Password, tokenId); } }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { X509Certificate2 solutionCertificate = parentAssertion.SolutionCertificate; solutionCertificateToken = new X509SecurityToken(solutionCertificate); sig = new MessageSignature(solutionCertificateToken); }
private XmlElement GetKeyIdentifierClause(X509SecurityToken certToken) { using (XmlDocumentWriterHelper documentWriterHelper = new XmlDocumentWriterHelper()) { // The key is located in the same XML document, so referencing that // with a local key identifier. var keyIdentifierClause = certToken.CreateKeyIdentifierClause <LocalIdKeyIdentifierClause>(); Debug.Assert(keyIdentifierClause != null); _tokenSerializer.WriteKeyIdentifierClause( documentWriterHelper.CreateDocumentWriter(), keyIdentifierClause); XmlDocument xmlDocument = documentWriterHelper.ReadDocument(); return(xmlDocument.DocumentElement); } }
private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (this.parent.RequireClientCertificate) { if (certificate == null) { if (DiagnosticUtility.ShouldTraceError) { TraceUtility.TraceEvent(TraceEventType.Error, 0x4002d, System.ServiceModel.SR.GetString("TraceCodeSslClientCertMissing"), this); } return(false); } X509Certificate2 certificate2 = new X509Certificate2(certificate); this.clientCertificate = certificate2; try { SecurityToken token = new X509SecurityToken(certificate2, false); ReadOnlyCollection <IAuthorizationPolicy> tokenPolicies = this.parent.ClientCertificateAuthenticator.ValidateToken(token); this.clientSecurity = new SecurityMessageProperty(); this.clientSecurity.TransportToken = new SecurityTokenSpecification(token, tokenPolicies); this.clientSecurity.ServiceSecurityContext = new ServiceSecurityContext(tokenPolicies); } catch (SecurityTokenException exception) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information); } return(false); } } return(true); }
private void InitializeServiceProxy() { // Create NodalService proxy reference _ercotClient = new NodalService(); // Load cert and sign SOAP message // clientCert = new X509Certificate2(@"C:\Projects\ErcotAPITestWS\ErcotAPITest\Cert\API_103_CERT.pfx", "a1e5i9"); _clientCert = new X509Certificate2(CLIENT_CERT_PATH, CLIENT_CERT_PASSWORD); _ercotMisApiCert = new X509Certificate2(@"C:\Projects\ErcotAPITestWS\ErcotAPITest\Cert\misapi.cer"); _ercotClient.ClientCertificates.Add(_clientCert); _ercotClient.ClientCertificates.Add(_ercotMisApiCert); _context = _ercotClient.RequestSoapContext; _token = new X509SecurityToken(_clientCert); _token2 = new X509SecurityToken(_ercotMisApiCert); //These are obsolete but necessary since they use old technology _context.Security.Tokens.Add(_token); _context.Security.Tokens.Add(_token2); _context.Security.Elements.Add(new MessageSignature(_token)); //Set TLS1.2 protocol ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // Handle service reply with a callback method _ercotClient.MarketInfoCompleted += this.ErcotClient_MarketInfoCompleted; }
private void CallWebService(int a, int b, string url) { // Instantiate an instance of the web service proxy AddNumbers serviceProxy = new AddNumbers(); SoapContext requestContext = serviceProxy.RequestSoapContext; // Get our security token X509SecurityToken token = GetSecurityToken(); if (token == null) { throw new ApplicationException("No key provided for signature."); } // Add the signature element to a security section on the request // to sign the request requestContext.Security.Tokens.Add(token); requestContext.Security.Elements.Add(new MessageSignature(token)); //requestContext.Timestamp.Ttl = 6000000; // Call the service if (url != null) { serviceProxy.Url = url; } Console.WriteLine("Calling {0}", serviceProxy.Url); int sum = serviceProxy.AddInt(a, b); // Success! string message = string.Format("{0} + {1} = {2}", a, b, sum); Console.WriteLine("Web Service returned: {0}", message); }
private X509SecurityToken getToken(string which) { X509SecurityToken token = null; X509CertificateStore store = null; string serverKeyIdentifier = "bBwPfItvKp3b6TNDq+14qs58VJQ="; //"po3h4Y4J8ITs/pW3acuRjpT8V1o="; string clientKeyIdentifier = "gBfo0147lM6cKnTbbMSuMVvmFY4="; //"Gu4aD7+bYTVtmSveoPIWTRtzD3M="; //string serverKeyIdentifier = "po3h4Y4J8ITs/pW3acuRjpT8V1o="; //string clientKeyIdentifier = "Gu4aD7+bYTVtmSveoPIWTRtzD3M="; store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore); store.OpenRead(); X509CertificateCollection coll; if (which == "server") { coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(serverKeyIdentifier)); } else { coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(clientKeyIdentifier)); } if (coll.Count > 0) { X509Certificate cert = (X509Certificate)coll[0]; RSA rsa = cert.Key; token = new X509SecurityToken(cert); } return(token); }
// callback from schannel private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (_parent.RequireClientCertificate) { if (certificate == null) { return(false); } // Note: add ref to handle since the caller will reset the cert after the callback return. X509Certificate2 certificate2 = new X509Certificate2(certificate); _clientCertificate = certificate2; try { SecurityToken token = new X509SecurityToken(certificate2, false); ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies; var validationValueTask = _parent.ClientCertificateAuthenticator.ValidateTokenAsync(token); authorizationPolicies = validationValueTask.IsCompleted ? validationValueTask.Result : validationValueTask.AsTask().GetAwaiter().GetResult(); _clientSecurity = new SecurityMessageProperty { TransportToken = new SecurityTokenSpecification(token, authorizationPolicies), ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies) }; } catch (SecurityTokenException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); return(false); } } return(true); }
// This method determines the security token that contains the key material that // the STS should encrypt a session key with in order // for the service the issued token is intended for to be able to extract that session key private SecurityToken GetEncryptingToken(Gudge.Samples.Security.RSTRSTR.RequestSecurityToken rst) { // If rst is null, we're toast if (rst == null) { throw new ArgumentNullException("rst"); } // Set encryptingToken to null SecurityToken encryptingToken = null; // ... Open the LocalMachine store in My for read-only access X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); // Find the "localhost" cert ... foreach (X509Certificate2 cert in store.Certificates) { if (cert.SubjectName.Name == "CN=RPKey") { // ... and set encryptingToken to that cert encryptingToken = new X509SecurityToken(cert); break; } } // Don't forget to close the store store.Close(); // return the token return(encryptingToken); }
// This method determines the security token that contains the key material that // the STS should sign the issued token with in order // for the service the issued token is intended for to trust that token private SecurityToken GetSigningToken() { // Set signingCert to null SecurityToken signingToken = null; // ... Open the LocalMachine store in My for read-only access X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); // Find the "STS" cert ... foreach (X509Certificate2 cert in store.Certificates) { if (cert.SubjectName.Name == "CN=IPKey") { // ... and set signingCert to that cert signingToken = new X509SecurityToken(cert); break; } } // Don't forget to close the store store.Close(); // return the token return(signingToken); }
public override string GetIssuerName(SecurityToken securityToken) { if (securityToken == null) { throw new ArgumentNullException("securityToken"); } X509SecurityToken token = securityToken as X509SecurityToken; if (token != null) { string thumbprint = token.Certificate.Thumbprint; if (this._configuredTrustedIssuers.ContainsKey(thumbprint)) { string str2 = this._configuredTrustedIssuers[thumbprint]; str2 = string.IsNullOrEmpty(str2) ? token.Certificate.Subject : str2; return(str2); } throw new KeyNotFoundException(string.Format("Could not find Thumbprint '{0}' in trusted issuers list : {1} :: Char Codes {2} vs {3}", thumbprint, string.Join(",", _configuredTrustedIssuers.Keys.ToArray <string>()), SamlHelpers.ToCompositeString(thumbprint), SamlHelpers.ToCompositeString(string.Join(",", _configuredTrustedIssuers.Keys.ToArray <string>())))); } //Throw our own exception to make it easier to debug throw new ArgumentException("Unable to validate token issuer the provided token was not a X509SecurityToken; cant determine the thumbprint to match", "securityToken"); }
protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token) { X509SecurityToken x509Token = (X509SecurityToken)token; this.validator.Validate(x509Token.Certificate); X509CertificateClaimSet x509ClaimSet = new X509CertificateClaimSet(x509Token.Certificate, this.cloneHandle); if (!this.mapToWindows) { return(SecurityUtils.CreateAuthorizationPolicies(x509ClaimSet, x509Token.ValidTo)); } WindowsClaimSet windowsClaimSet; if (token is X509WindowsSecurityToken) { windowsClaimSet = new WindowsClaimSet(((X509WindowsSecurityToken)token).WindowsIdentity, SecurityUtils.AuthTypeCertMap, this.includeWindowsGroups, this.cloneHandle); } else { // Ensure NT_AUTH chain policy for certificate account mapping X509CertificateValidator.NTAuthChainTrust.Validate(x509Token.Certificate); WindowsIdentity windowsIdentity = null; // for Vista, LsaLogon supporting mapping cert to NTToken if (Environment.OSVersion.Version.Major >= SecurityUtils.WindowsVistaMajorNumber) { windowsIdentity = KerberosCertificateLogon(x509Token.Certificate); } else { // Downlevel, S4U over PrincipalName SubjectAltNames string name = x509Token.Certificate.GetNameInfo(X509NameType.UpnName, false); if (string.IsNullOrEmpty(name)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.InvalidNtMapping, SecurityUtils.GetCertificateId(x509Token.Certificate)))); } using (WindowsIdentity initialWindowsIdentity = new WindowsIdentity(name, SecurityUtils.AuthTypeCertMap)) { // This is to make sure that the auth Type is shoved down to the class as the above constructor does not do it. windowsIdentity = new WindowsIdentity(initialWindowsIdentity.Token, SecurityUtils.AuthTypeCertMap); } } windowsClaimSet = new WindowsClaimSet(windowsIdentity, SecurityUtils.AuthTypeCertMap, this.includeWindowsGroups, false); } List <ClaimSet> claimSets = new List <ClaimSet>(2); claimSets.Add(windowsClaimSet); claimSets.Add(x509ClaimSet); List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1); policies.Add(new UnconditionalPolicy(claimSets.AsReadOnly(), x509Token.ValidTo)); return(policies.AsReadOnly()); }
public override string GetIssuerName(SecurityToken securityToken) { X509SecurityToken x509Token = securityToken as X509SecurityToken; if (x509Token != null) { // The following check is to allow only trusted issuers of the STS token if (String.Equals(x509Token.Certificate.SubjectName.Name, "CN=localhost")) { return(x509Token.Certificate.SubjectName.Name); } // The following check is to allow only trusted issuers for the client certificate. if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.ClientCertificate != null && HttpContext.Current.Request.ClientCertificate.IsPresent && HttpContext.Current.Request.ClientCertificate.IsValid) { X509Certificate2 clientCertificate = new X509Certificate2(HttpContext.Current.Request.ClientCertificate.Certificate); // Get the issuer of the client certificate X509Chain chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.Build(clientCertificate); X509ChainElementCollection elements = chain.ChainElements; X509Certificate2 issuerCert = null; if (elements.Count > 1) { issuerCert = elements[1].Certificate; } else { // This is a self-issued certificate. issuerCert = clientCertificate; } string issuerCertThumbprint = issuerCert.Thumbprint; // Reset the state of the certificate and free resources associated with it. for (int i = 1; i < elements.Count; ++i) { elements[i].Certificate.Reset(); } // The implementation below currently accepts all client certificates and returns the SubjectName as the issuer name. This is intended only for illustration purposes. // In production, consider doing additional validation based on the issuer of the client certificate to return an appropriate issuer name. // DO NOT use this sample code ‘as is’ in production code. // Ensure that the issuer of the client certificate as obtained from the transport, matches the issuer token passed in to this method. if (!StringComparer.Ordinal.Equals(issuerCertThumbprint, x509Token.Certificate.Thumbprint)) { throw new SecurityTokenException("Issuer of the client certificate as obtained from the transport does not match the issuer token passed in to this method."); } return(x509Token.Certificate.SubjectName.Name); } } throw new SecurityTokenException("Untrusted issuer."); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { String username = parentAssertion.username; String password = parentAssertion.password; userToken = new UsernameToken(username.Trim(), password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken("CN=TestSSSCert"); sig = new MessageSignature(signatureToken); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { if (parentAssertion.BinaryToken == null) { userToken = new UsernameToken(parentAssertion.Username.Trim(), parentAssertion.Password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken(); parentAssertion.SecurityToken = signatureToken; } else { issuedToken = new IssuedToken(parentAssertion.BinaryToken); signatureToken = parentAssertion.SecurityToken; samlAssertionId = parentAssertion.BinaryToken.Attributes.GetNamedItem("ID").Value; } sig = new MessageSignature(signatureToken); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { signatureToken = GetSecurityToken(); sig = new MessageSignature(signatureToken); }
/// <summary> /// Returns the X.509 SecurityToken that will be used to encrypt the /// messages. /// </summary> /// <returns>Returns </returns> public X509SecurityToken GetEncryptionToken() { X509SecurityToken token = null; // // The certificate for the target receiver should have been imported // into the "My" certificate store. This store is listed as "Personal" // in the Certificate Manager // X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore); bool open = store.OpenRead(); try { // // Open a dialog to allow user to select the certificate to use // StoreDialog dialog = new StoreDialog(store); X509Certificate cert = dialog.SelectCertificate(IntPtr.Zero, "Select Certificate", "Choose a Certificate below for encrypting."); if (cert == null) { throw new ApplicationException("You chose not to select an X509 certificate for encrypting your messages."); } else if (!cert.SupportsDataEncryption) { throw new ApplicationException("The certificate must support key encipherment."); } else { token = new X509SecurityToken(cert); } } finally { if (store != null) { store.Close(); } } return token; }
/// <summary> /// This method is used to extract the security token from certificate /// </summary> /// <param name="subjectName">string</param> internal static X509SecurityToken GetSecurityToken(string subjectName) { X509SecurityToken securityToken = null; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); X509Certificate2 certToBeAdded = new X509Certificate2(ValidateTokenSample.Properties.Resources._1234); store = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Add(certToBeAdded); store.Open(OpenFlags.ReadOnly); try { X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false); X509Certificate2 cert; if (certs.Count == 1) { cert = certs[0]; securityToken = new X509SecurityToken(cert); } else { securityToken = null; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (store != null) store.Close(); } return securityToken; }
private X509SecurityToken getToken(string which) { X509SecurityToken token = null; X509CertificateStore store = null; string serverKeyIdentifier = "bBwPfItvKp3b6TNDq+14qs58VJQ="; //"po3h4Y4J8ITs/pW3acuRjpT8V1o="; string clientKeyIdentifier = "gBfo0147lM6cKnTbbMSuMVvmFY4="; //"Gu4aD7+bYTVtmSveoPIWTRtzD3M="; //string serverKeyIdentifier = "po3h4Y4J8ITs/pW3acuRjpT8V1o="; //string clientKeyIdentifier = "Gu4aD7+bYTVtmSveoPIWTRtzD3M="; store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore); store.OpenRead(); X509CertificateCollection coll; if (which == "server") { coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(serverKeyIdentifier)); } else { coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(clientKeyIdentifier)); } if (coll.Count > 0) { X509Certificate cert = (X509Certificate) coll[0]; RSA rsa = cert.Key; token = new X509SecurityToken(cert); } return token; }
private static X509SecurityToken RetrieveTokenFromStore (X509CertificateStore store, string keyIdentifier) { if (store == null) throw new ArgumentNullException ("store"); X509SecurityToken token = null; try { if (store.OpenRead ()) { // Place the key ID of the certificate in a byte array // This KeyID represents the Wse2Quickstart certificate included with the WSE 2.0 Quickstarts // ClientBase64KeyId is defined in the ClientBase.AppBase class X509CertificateCollection certs = store.FindCertificateByKeyIdentifier (Convert.FromBase64String (keyIdentifier)); if (certs.Count > 0) { // Get the first certificate in the collection token = new X509SecurityToken (((X509Certificate) certs[0])); } } } finally { if (store != null) store.Close (); } return token; }
/// <summary> /// Gets the security token for signing messages. /// </summary> /// <returns>Returns </returns> public X509SecurityToken GetSecurityToken() { X509SecurityToken securityToken; // // open the current user's certificate store // X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore); bool open = store.OpenRead(); try { // // Open a dialog to allow user to select the certificate to use // StoreDialog dialog = new StoreDialog(store); X509Certificate cert = dialog.SelectCertificate(IntPtr.Zero, "Select Certificate", "Choose a Certificate below for signing."); if (cert == null) { throw new ApplicationException("You chose not to select an X509 certificate for signing your messages."); } else if (!cert.SupportsDigitalSignature) { throw new ApplicationException("The certificate must support digital signatures and have a private key available."); } else { securityToken = new X509SecurityToken(cert); } } finally { if (store != null) { store.Close(); } } return securityToken; }