public static JwksKeyModel FromSigningCredentials(X509SigningCredentials signingCredentials) { var certificate = signingCredentials.Certificate; // JWK cert data must be base64 (not base64url) encoded var certData = Convert.ToBase64String(certificate.Export(X509ContentType.Cert)); // JWK thumbprints must be base64url encoded (no padding or special chars) var thumbprint = Base64UrlEncoder.Encode(certificate.GetCertHash()); // JWK must have the modulus and exponent explicitly defined var rsa = certificate.GetRSAPublicKey() as RSACng; if (rsa == null) { throw new Exception("Certificate is not an RSA certificate."); } var keyParams = rsa.ExportParameters(false); var keyModulus = Base64UrlEncoder.Encode(keyParams.Modulus); var keyExponent = Base64UrlEncoder.Encode(keyParams.Exponent); return(new JwksKeyModel { Kid = signingCredentials.Kid, Kty = "RSA", Nbf = new DateTimeOffset(certificate.NotBefore).ToUnixTimeSeconds(), Use = "sig", Alg = signingCredentials.Algorithm, X5C = new[] { certData }, X5T = thumbprint, N = keyModulus, E = keyExponent }); }
public string GenerateJwt(ClaimsIdentity claims, int tokenExpiry, string key = null, X509Certificate2 signingCertificate = null) { SigningCredentials signingCredentials = null; if (key != null) { signingCredentials = new SigningCredentials( new SymmetricSecurityKey(Encoding.Default.GetBytes(key)), SecurityAlgorithms.HmacSha256Signature); } else if (signingCertificate != null) { signingCredentials = new X509SigningCredentials(signingCertificate); } else if (key != null && signingCertificate != null) { throw new ArgumentException("Cannot pass both a certificate and key"); } var jwtHandler = new JwtSecurityTokenHandler(); var tokenDesc = new SecurityTokenDescriptor { SigningCredentials = signingCredentials, Subject = claims, Expires = DateTime.UtcNow.AddMinutes(15) }; var t = jwtHandler.CreateToken(tokenDesc); string token = jwtHandler.WriteToken(t); return(token); }
/// <summary> /// Creates a SAML assertion signed with the given certificate. /// </summary> public static Saml2SecurityToken GetSamlAssertionSignedWithCertificate(String nameIdentifierClaim, byte[] certificateWithPrivateKeyRawBytes, string password) { string acsUrl = string.Format(CultureInfo.InvariantCulture, "https://{0}.{1}", SamplesConfiguration.ServiceNamespace, SamplesConfiguration.AcsHostUrl); Saml2Assertion assertion = new Saml2Assertion(new Saml2NameIdentifier(nameIdentifierClaim)); Saml2Conditions conditions = new Saml2Conditions(); conditions.NotBefore = DateTime.UtcNow; conditions.NotOnOrAfter = DateTime.MaxValue; conditions.AudienceRestrictions.Add(new Saml2AudienceRestriction(new Uri(acsUrl, UriKind.RelativeOrAbsolute))); assertion.Conditions = conditions; Saml2Subject subject = new Saml2Subject(); subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(Saml2Constants.ConfirmationMethods.Bearer)); subject.NameId = new Saml2NameIdentifier(nameIdentifierClaim); assertion.Subject = subject; X509SigningCredentials clientSigningCredentials = new X509SigningCredentials( new X509Certificate2(certificateWithPrivateKeyRawBytes, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable)); assertion.SigningCredentials = clientSigningCredentials; return(new Saml2SecurityToken(assertion)); }
/// <summary> /// Creates a SAML assertion signed with the given certificate. /// </summary> public static Saml2SecurityToken CreateSaml2SecurityToken(byte[] certificate, string password, params Claim[] claims) { const string acsUrl = "http://blueprintsys.com"; var assertion = new Saml2Assertion(new Saml2NameIdentifier(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 JwksKey FromSigningCredentials(X509SigningCredentials signingCredentials) { X509Certificate2 certificate = signingCredentials.Certificate; // JWK cert data must be base64 (not base64url) encoded string certData = Convert.ToBase64String(certificate.Export(X509ContentType.Cert)); // JWK thumbprints must be base64url encoded (no padding or special chars) string thumbprint = Base64UrlEncoder.Encode(certificate.GetCertHash()); // JWK must have the modulus and exponent explicitly defined RSACryptoServiceProvider publicKey = certificate.PublicKey.Key as RSACryptoServiceProvider; if (publicKey == null) { throw new Exception("Certificate is not an RSA certificate."); } RSAParameters keyParams = publicKey.ExportParameters(false); string keyModulus = Base64UrlEncoder.Encode(keyParams.Modulus); string keyExponent = Base64UrlEncoder.Encode(keyParams.Exponent); var certnbf = (certificate.NotBefore).Ticks; return(new JwksKey { Kid = signingCredentials.Kid, Kty = "RSA", Nbf = 1555712377, Use = "sig", Alg = signingCredentials.Algorithm, X5C = new[] { certData }, X5T = thumbprint, N = keyModulus, E = keyExponent }); }
public static async Task Main() { Console.Title = "Console Client Credentials Flow with JWT Assertion"; // X.509 cert var certificate = new X509Certificate2("client.p12", "changeit"); var x509Credential = new X509SigningCredentials(certificate); var response = await RequestTokenAsync(x509Credential); response.Show(); Console.ReadLine(); await CallServiceAsync(response.AccessToken); // RSA JsonWebkey var jwk = new JsonWebKey(rsaKey); response = await RequestTokenAsync(new SigningCredentials(jwk, "RS256")); response.Show(); Console.ReadLine(); await CallServiceAsync(response.AccessToken); }
/// <summary> /// Create signing credentials /// </summary> private SigningCredentials CreateSigningCredentials() { SigningCredentials retVal = null; // Signing credentials if (this.m_configuration.Certificate != null) { retVal = new X509SigningCredentials(this.m_configuration.Certificate); } else if (!String.IsNullOrEmpty(this.m_configuration.ServerSecret) || this.m_configuration.ServerKey != null) { var sha = SHA256.Create(); retVal = new SigningCredentials( new InMemorySymmetricSecurityKey(this.m_configuration.ServerKey ?? sha.ComputeHash(Encoding.UTF8.GetBytes(this.m_configuration.ServerSecret))), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256", new SecurityKeyIdentifier(new NamedKeySecurityKeyIdentifierClause("keyid", "0")) ); } else { throw new SecurityException("Invalid signing configuration"); } return(retVal); }
public TokenServiceConfiguration() : base() { Tracing.Information("Configuring token service"); Container.Current.SatisfyImportsOnce(this); SecurityTokenService = typeof(TokenService); DefaultTokenLifetime = TimeSpan.FromHours(ConfigurationRepository.Global.DefaultTokenLifetime); MaximumTokenLifetime = TimeSpan.FromDays(ConfigurationRepository.Global.MaximumTokenLifetime); DefaultTokenType = ConfigurationRepository.Global.DefaultWSTokenType; TokenIssuerName = ConfigurationRepository.Global.IssuerUri; SigningCredentials = new X509SigningCredentials(ConfigurationRepository.Keys.SigningCertificate); if (ConfigurationRepository.WSTrust.EnableDelegation) { Tracing.Information("Configuring identity delegation support"); try { var actAsRegistry = new ConfigurationBasedIssuerNameRegistry(); actAsRegistry.AddTrustedIssuer(ConfigurationRepository.Keys.SigningCertificate.Thumbprint, ConfigurationRepository.Global.IssuerUri); var actAsHandlers = SecurityTokenHandlerCollectionManager["ActAs"]; actAsHandlers.Configuration.IssuerNameRegistry = actAsRegistry; actAsHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never; } catch (Exception ex) { Tracing.Error("Error configuring identity delegation"); Tracing.Error(ex.ToString()); throw; } } }
public TokenServiceConfiguration() : base() { Tracing.Information("Configuring token service"); Container.Current.SatisfyImportsOnce(this); GlobalConfiguration = ConfigurationRepository.Configuration; SecurityTokenService = typeof(TokenService); DefaultTokenLifetime = TimeSpan.FromHours(GlobalConfiguration.DefaultTokenLifetime); MaximumTokenLifetime = TimeSpan.FromDays(GlobalConfiguration.MaximumTokenLifetime); DefaultTokenType = GlobalConfiguration.DefaultTokenType; TokenIssuerName = GlobalConfiguration.IssuerUri; SigningCredentials = new X509SigningCredentials(ConfigurationRepository.SigningCertificate.Certificate); if (GlobalConfiguration.EnableDelegation) { Tracing.Information("Configuring identity delegation support"); try { var actAsRegistry = new ConfigurationBasedIssuerNameRegistry(); actAsRegistry.AddTrustedIssuer(ConfigurationRepository.SigningCertificate.Certificate.Thumbprint, GlobalConfiguration.IssuerUri); var actAsHandlers = SecurityTokenHandlerCollectionManager["ActAs"]; actAsHandlers.Configuration.IssuerNameRegistry = actAsRegistry; actAsHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never; } catch (Exception ex) { Tracing.Error("Error configuring identity delegation"); Tracing.Error(ex.ToString()); throw; } } }
public static JwtSecurityToken CreateToken( string issuer = null, string audience = null, IEnumerable <string> scope = null, int ttl = 360, List <Claim> additionalClaims = null, X509Certificate2 signingCertificate = null) { if (additionalClaims == null) { additionalClaims = new List <Claim>(); } if (scope != null && scope.Any()) { scope.ToList().ForEach(s => additionalClaims.Add(new Claim("scope", s))); } var credential = new X509SigningCredentials(signingCertificate ?? DefaultSigningCertificate); var token = new JwtSecurityToken( issuer ?? DefaultIssuer, audience ?? DefaultAudience, additionalClaims, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(ttl), credential); token.Header.Add( "kid", Base64Url.Encode(credential.Certificate.GetCertHash())); return(token); }
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); }
private SigningCredentials GetSigningCredentials() { X509Certificate2 cert = new X509Certificate2("C:\\Repos\\JWTAspNetCore\\JWTAspNetCore\\jwtselfsignedcert.pfx", "qwer1234"); SigningCredentials creds = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256); return(creds); }
public void Run() { var x509Certificate2 = new X509Certificate2(@"{FILE PATH}\office_365_app.pfx", "PASS_WORD"); X509SigningCredentials signingCredentials = new X509SigningCredentials(x509Certificate2, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); var originalIssuer = "{YOUR CLIENT ID}"; var issuer = originalIssuer; DateTime utcNow = DateTime.UtcNow; DateTime expired = utcNow + TimeSpan.FromHours(1); var claims = new List <Claim> { new Claim("aud", "https://login.microsoftonline.com/{YOUR_TENENT_ID}/oauth2/token", ClaimValueTypes.String, issuer, originalIssuer), new Claim("exp", "1460534173", ClaimValueTypes.DateTime, issuer, originalIssuer), new Claim("jti", "{SOME GUID YOU ASSIGN}", ClaimValueTypes.String, issuer, originalIssuer), new Claim("nbf", "1460533573", ClaimValueTypes.String, issuer, originalIssuer), new Claim("sub", "{YOUR CLIENT ID}", ClaimValueTypes.String, issuer, originalIssuer) }; ClaimsIdentity subject = new ClaimsIdentity(claims: claims); JwtSecurityToken jwtToken = tokenHandler.CreateToken( issuer: issuer, signingCredentials: signingCredentials, subject: subject) as JwtSecurityToken; jwtToken.Header.Remove("typ"); var token = tokenHandler.WriteToken(jwtToken); }
static void Main(string[] args) { SigningCredentials signingCreds = new X509SigningCredentials("CN=MySTS".ToCertificate()); SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration("http://MySTS", signingCreds); config.SecurityTokenHandlers.AddOrReplace(new CustomUsernameTokenHandler()); config.SecurityTokenService = typeof(MySecurityTokenService); // Create the WS-Trust service host with our STS configuration var host = new WSTrustServiceHost(config, new Uri("http://localhost:6000/MySTS")); try { host.Open(); Console.WriteLine("STS is ready to issue tokens… Press ENTER to shutdown"); Console.ReadLine(); host.Close(); } finally { if (host.State != CommunicationState.Faulted) { host.Close(); } else { host.Abort(); } } }
public static async Task Main() { Console.Title = "Console Client Credentials Flow with JWT Assertion"; // X.509 cert // var certificate = new X509Certificate2("client.p12", "changeit"); var certificate = new X509Certificate2("Andreas_Orzelski_Chain.pfx", "i40"); // var x509Credential = new X509SigningCredentials(certificate); X509SigningCredentials x509Credential = null; var response = await RequestTokenAsync(x509Credential); response.Show(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nPress ENTER to access Aasx Server at " + baseAddress + "\n"); Console.ResetColor(); Console.ReadLine(); await CallServiceAsync(response.AccessToken); /* * // RSA JsonWebkey * var jwk = new JsonWebKey(rsaKey); * response = await RequestTokenAsync(new SigningCredentials(jwk, "RS256")); * response.Show(); * * Console.ReadLine(); * await CallServiceAsync(response.AccessToken); */ }
private static string SignMessage(byte[] message, X509SigningCredentials x509SigningCredentials) { using var key = x509SigningCredentials.Certificate.GetRSAPrivateKey(); var signedMessage = Convert.ToBase64String(key?.SignData(message, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1) ?? Array.Empty <byte>()); return(signedMessage); }
private static X509SigningCredentials GetX509SigningCredentials() { var certificate = X509Certificate2.CreateFromPem(CertificatePublicKey, PrivateKey); var signingCredentials = new X509SigningCredentials(certificate, SecurityAlgorithms.RsaSha256Signature); return(signingCredentials); }
public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate) { var credentials = new X509SigningCredentials(signingCertificate); // Figure out the hostname exposed from Azure and what port the service is listening on var realm = new EndpointAddress(identifier); var passiveEndpoint = new EndpointReference(passiveSignInUrl.AbsoluteUri); // Create metadata document for relying party var entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri)); var securityTokenServiceDescriptor = CreateSecurityTokenServiceDescriptor(credentials, passiveEndpoint); var applicationServiceDescriptor = CreateApplicationServiceDescriptor(); var serviceProviderSingleSignOnDescriptor = CreateServiceProviderSingleSignOnDescriptor(); entity.RoleDescriptors.Add(securityTokenServiceDescriptor); entity.RoleDescriptors.Add(applicationServiceDescriptor); entity.RoleDescriptors.Add(serviceProviderSingleSignOnDescriptor); // Set credentials with which to sign the metadata entity.SigningCredentials = credentials; // Serialize the metadata and convert it to an XElement var serializer = new MetadataSerializer(); var stream = new MemoryStream(); serializer.WriteMetadata(stream, entity); stream.Flush(); return(stream.ToArray()); }
public static TestSts Create() { var signingCredentials = new X509SigningCredentials(GetCertificate()); var configuration = new SecurityTokenServiceConfiguration(Issuer, signingCredentials); return(new TestSts(configuration)); }
public SimpleSecurityTokenServiceConfiguration() { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var credCert = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, "sign.idp.prompt11.local", true)[0]; SigningCredentials = new X509SigningCredentials(credCert); // HACK: fazer tambem Add Reference - System.IdentityModel }
private static SigningCredentials CreateSigningCredentials() { var certificate = new X509Certificate2(@"MyCA.pfx", "mypassword"); var signingCreds = new X509SigningCredentials(certificate, SecurityAlgorithms.RsaSha256Signature); return(signingCreds); }
//Assymetric public static JwtToken CreateJwtTokenSigningWithCertificateSecurityKey(string userId, string userName, string email, IEnumerable <string> roles, int?minuteExpiry, X509SecurityKey key, string issuer, string audience, params string[] scopes) { var claims = GetClaims(userId, userName, email, roles, scopes); var creds = new X509SigningCredentials(key.Certificate, SecurityAlgorithms.RsaSha256); // JwtSecurityTokenHandler will serialize X509SigningCredentials kid=key.KeyId(Thumbprint) and x5t=key.X5t(cert hash), it wont serialize x5t for SigningCredentials creds.Key.KeyId = key.KeyId; return(CreateJwtToken(minuteExpiry, issuer, audience, claims, creds)); }
private void FetchKeyWithJWTAuth(string audience, string issuer) { IContentKey contentKey = null; IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null; IContentKeyAuthorizationPolicyOption policyOption = null; try { byte[] expectedKey = null; contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey); var templatex509Certificate2 = new X509Certificate2("amscer.pfx", "AMSGIT"); SigningCredentials cred = new X509SigningCredentials(templatex509Certificate2); TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT); tokenRestrictionTemplate.PrimaryVerificationKey = new X509CertTokenVerificationKey(templatex509Certificate2); tokenRestrictionTemplate.Audience = audience; tokenRestrictionTemplate.Issuer = issuer; string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication"; string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate); policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted); JwtSecurityToken token = new JwtSecurityToken(issuer: tokenRestrictionTemplate.Issuer, audience: tokenRestrictionTemplate.Audience, notBefore: DateTime.Now.AddMinutes(-5), expires: DateTime.Now.AddMinutes(5), signingCredentials: cred); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); string jwtTokenString = handler.WriteToken(token); List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption> { policyOption }; contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey); Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp); Assert.IsNotNull(keyDeliveryServiceUri); // Enable once all accounts are enabled for per customer Key Delivery Urls //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId)); KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed); byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString); string expectedString = GetString(expectedKey); string fetchedString = GetString(key); Assert.AreEqual(expectedString, fetchedString); } finally { CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption); } }
public static string ProcessSignIn(Uri url, ClaimsPrincipal user) { var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url); var signingCredentials = new X509SigningCredentials(CustomSecurityTokenService.GetCertificate2()); var config = new SecurityTokenServiceConfiguration($"{url.Scheme}://{url.Authority}/FederatedLogin/", signingCredentials); var sts = new CustomSecurityTokenService(config); var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts); return(responseMessage.WriteFormPost()); }
private SecurityTokenServiceConfiguration GetSecureTokenServiceConfiguration() { var signingCredentials = new X509SigningCredentials(CertificateHelper.GetCertificate(_tokenServiceOptions.CertificateStoreName, _tokenServiceOptions.CertificateStoreLocation, _tokenServiceOptions.CertificateSubject)); var config = new SecurityTokenServiceConfiguration(_tokenServiceOptions.CertificateIssuer, signingCredentials); config.SecurityTokenHandlers.AddOrReplace(_unityContainer.Resolve <CustomAuthenticationHandler>()); config.SecurityTokenService = typeof(TokenService); config.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; return(config); }
private static string ProcessSignIn(Uri url, ClaimsPrincipal user) { var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url); var signingCredentials = new X509SigningCredentials(CustomSecurityTokenService.GetCertificate(ConfigurationManager.AppSettings["SigningCertificateName"])); var config = new SecurityTokenServiceConfiguration(ConfigurationManager.AppSettings["IssuerName"], signingCredentials); var sts = new CustomSecurityTokenService(config); var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts); return(responseMessage.WriteFormPost()); }
private static string CreateClientToken(SigningCredentials credential, string clientId, string audience) { // oz string x5c = ""; string certFileName = "Andreas_Orzelski_Chain.pfx"; string password = "******"; X509Certificate2Collection xc = new X509Certificate2Collection(); xc.Import(certFileName, password, X509KeyStorageFlags.PersistKeySet); string[] X509Base64 = new string[xc.Count]; int j = xc.Count; var xce = xc.GetEnumerator(); for (int i = 0; i < xc.Count; i++) { xce.MoveNext(); X509Base64[--j] = Convert.ToBase64String(xce.Current.GetRawCertData()); } x5c = JsonConvert.SerializeObject(X509Base64); // Byte[] certFileBytes = Convert.FromBase64String(X509Base64[0]); // credential = new X509SigningCredentials(new X509Certificate2(certFileBytes)); credential = new X509SigningCredentials(new X509Certificate2(certFileName, password)); // oz end var now = DateTime.UtcNow; var token = new JwtSecurityToken( clientId, audience, new List <Claim>() { new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()), new Claim(JwtClaimTypes.Subject, clientId), new Claim(JwtClaimTypes.IssuedAt, now.ToEpochTime().ToString(), ClaimValueTypes.Integer64), // OZ new Claim(JwtClaimTypes.Email, "*****@*****.**") // new Claim("x5c", x5c) }, now, now.AddMinutes(1), credential) ; token.Header.Add("x5c", x5c); // oz var tokenHandler = new JwtSecurityTokenHandler(); return(tokenHandler.WriteToken(token)); }
protected void btnIssue_Click(object sender, EventArgs e) { X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=localhost"); // // The WS-Identity schema requires cards to be signed using SHA-1. // X509SigningCredentials signingCredentials = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest); // // Create an InformationCard // InformationCard card = new InformationCard(signingCredentials, UserNameCardStsHostFactory.StsAddress); card.CardImage = new CardImage(Context.Request.PhysicalApplicationPath + @"\information-card.png"); card.CardName = "CustomUserNameCardStsHostFactory Managed Card"; card.TimeExpires = card.TimeIssued.Value + TimeSpan.FromDays(7.0); // one week card.Language = "en-us"; card.TokenServiceList.Add(new TokenService(new TokenServiceEndpoint(UserNameCardStsHostFactory.StsAddress, UserNameCardStsHostFactory.StsMexAddress, UserCredentialType.UserNamePasswordCredential, cert), new UserNamePasswordCredential("terry"))); List <string> claimTypes = new List <string>(); claimTypes.Add(ClaimTypes.GivenName); claimTypes.Add(ClaimTypes.Surname); claimTypes.Add(ClaimTypes.PPID); claimTypes.Add(ClaimTypes.HomePhone); card.SupportedClaimTypeList.AddRange(GetDisplayClaimsFromClaimTypes(claimTypes)); IEnumerable <SecurityTokenHandlerCollection> handlersList = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlerCollectionManager.SecurityTokenHandlerCollections; foreach (SecurityTokenHandlerCollection handlers in handlersList) { if (null != handlers) { foreach (string tokenType in handlers.TokenTypeIdentifiers) { card.SupportedTokenTypeList.Add(tokenType); } } } // // This writes the card out in XML as a .CRD file into the HTTP response. // Internet Explorer will recognize the MIME type and prompt the user. // InformationCardSerializer serializer = new InformationCardSerializer(); Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment; filename=InformationCard.crd"); Response.ContentType = "application/x-informationcardfile"; serializer.WriteCard(Response.OutputStream, card); Response.End(); }
public VkSecurityTokenServiceConfiguration() { TokenIssuerName = VkClaims.IssuerName; string signingCertificatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Constants.SigningCertificate); var signignCert = new X509Certificate2(signingCertificatePath, Constants.SigningCertificatePassword, X509KeyStorageFlags.PersistKeySet); SigningCredentials = new X509SigningCredentials(signignCert); ServiceCertificate = signignCert; SecurityTokenService = typeof(VkSecurityTokenService); }
/// <summary> /// Create signing credentials /// </summary> /// <param name="keyName">The name of the key to use in the configuration, or null to use a default key</param> public static SigningCredentials CreateSigningCredentials(string keyName) { var configuration = ApplicationContext.Current.GetService <IConfigurationManager>().GetSection <SecurityConfigurationSection>().Signatures.FirstOrDefault(o => o.KeyName == keyName); // No configuration found for this key if (configuration == null) { return(null); } // No specific configuration for the key name is found? SigningCredentials retVal = null; // Signing credentials switch (configuration.Algorithm) { case SignatureAlgorithm.RS256: case SignatureAlgorithm.RS512: var cert = configuration.Certificate; if (cert == null) { throw new SecurityException("Cannot find certificate to sign data!"); } // Signature algorithm string signingAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256"; if (configuration.Algorithm == SignatureAlgorithm.RS512) { signingAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha512"; } retVal = new X509SigningCredentials(cert, new SecurityKeyIdentifier(new NamedKeySecurityKeyIdentifierClause("name", configuration.KeyName ?? "0")), signingAlgorithm, digestAlgorithm); break; case SignatureAlgorithm.HS256: byte[] secret = configuration.Secret.ToArray(); while (secret.Length < 16) { secret = secret.Concat(secret).ToArray(); } retVal = new SigningCredentials( new InMemorySymmetricSecurityKey(secret), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256", new SecurityKeyIdentifier(new NamedKeySecurityKeyIdentifierClause("name", configuration.KeyName ?? "0")) ); break; default: throw new SecurityException("Invalid signing configuration"); } return(retVal); }
public SamlTokenServiceConfiguration(string issuerName) { Tracing.Information("Configuring token service"); Container.Current.SatisfyImportsOnce(this); SecurityTokenService = typeof(SamlTokenService); DefaultTokenLifetime = TimeSpan.FromHours(ConfigurationRepository.Global.DefaultTokenLifetime); MaximumTokenLifetime = TimeSpan.FromDays(ConfigurationRepository.Global.MaximumTokenLifetime); DefaultTokenType = ConfigurationRepository.Global.DefaultWSTokenType; TokenIssuerName = issuerName; SigningCredentials = new X509SigningCredentials(ConfigurationRepository.Keys.SigningCertificate); }
//private string GetJwtFromCode(string codeFromPost, HttpContextBase context) //{ // AADOAuth2AccessToken accessToken = new AADOAuth2AccessToken(); // if (_tokenCaches.TryGetValue(codeFromPost, out accessToken) ) // { // if (accessToken.IsValid()) // return accessToken.access_token; // } // // "token_endpoint":"https://login.windows-ppe.net/common/oauth2/token" // var tokenRequestUri = GetTokenEndpoint(AuthSettings.AADTokenEndpoint) ; // string jwt = GetJwt(audience: tokenRequestUri); // var redirectUri = string.Format(CultureInfo.InvariantCulture, "https://{0}/", context.Request.Headers["HOST"]); // var payload = new StringBuilder("grant_type=authorization_code"); // payload.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(SimpleWAWS.Models.Util.PunicodeUrl(redirectUri))); // payload.AppendFormat("&code={0}", WebUtility.UrlEncode(codeFromPost)); // payload.AppendFormat("&client_assertion_type={0}", WebUtility.UrlEncode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")); // payload.AppendFormat("&client_assertion={0}", WebUtility.UrlEncode(jwt)); // var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); // using (var client = new HttpClient()) // { // client.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString()); // client.DefaultRequestHeaders.Add("User-Agent", "Try App Service"); // using (var response = client.PostAsync(tokenRequestUri, content).ConfigureAwait(false).GetAwaiter().GetResult()) // { // if (!response.IsSuccessStatusCode) // { // return HandleOAuthError(response, tokenRequestUri).ConfigureAwait(false).GetAwaiter().GetResult(); // } // var result = response.Content.ReadAsAsync<AADOAuth2AccessToken>().ConfigureAwait(false).GetAwaiter().GetResult(); // //result.TenantId = tenantId != "common" ? tenantId : GetTenantIdFromToken(result.access_token); // _tokenCaches.Add(codeFromPost, result); // return result.access_token; // } // } // //return null; //} static string GetJwt(string audience) { string clientId = AuthSettings.AADAppId; var claims = new List <System.Security.Claims.Claim>(); claims.Add(new System.Security.Claims.Claim("sub", clientId)); claims.Add(new System.Security.Claims.Claim("jti", Guid.NewGuid().ToString())); // RFC 7519: https://tools.ietf.org/html/rfc7519#section-4.1.7 var handler = new JwtSecurityTokenHandler(); var credentials = new X509SigningCredentials(GetCertificate(AuthSettings.AADAppCertificateThumbprint)); return(handler.CreateToken(clientId, audience, new ClaimsIdentity(claims), null, credentials).RawData); }
public CustomSecurityTokenServiceConfiguration() { AudienceRestriction.AudienceMode = AudienceUriMode.Never; CertificateValidationMode = X509CertificateValidationMode.None; IssuerNameRegistry = new FakeIssuerNameRegistry(); SecurityTokenService = typeof(CustomSecurityTokenService); DefaultTokenLifetime = Configuration.PersistentSessionLength; MaximumTokenLifetime = Configuration.PersistentSessionLength; TokenIssuerName = Configuration.IssuerName; SigningCredentials = new X509SigningCredentials(Configuration.TokenSigningCertificate); var actAsHandlers = new SecurityTokenHandlerCollection(new SecurityTokenHandler[] { new Saml11SecurityTokenHandler(), new Saml2SecurityTokenHandler() }); actAsHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never; actAsHandlers.Configuration.CertificateValidator = X509CertificateValidator.None; actAsHandlers.Configuration.IssuerNameRegistry = new FakeIssuerNameRegistry(); SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.ActAs] = actAsHandlers; }
public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate) { var credentials = new X509SigningCredentials(signingCertificate); // Figure out the hostname exposed from Azure and what port the service is listening on EndpointAddress realm = new EndpointAddress(identifier); EndpointAddress passiveEndpoint = new EndpointAddress(passiveSignInUrl); // Create metadata document for relying party EntityDescriptor entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri)); SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor(); entity.RoleDescriptors.Add(sts); // Add STS's signing key KeyDescriptor signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier); signingKey.Use = KeyType.Signing; sts.Keys.Add(signingKey); // Add offered claim types sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod)); sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant)); sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name)); // Add passive federation endpoint sts.PassiveRequestorEndpoints.Add(passiveEndpoint); // Add supported protocols sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace)); // Add passive STS endpoint sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint); // Set credentials with which to sign the metadata entity.SigningCredentials = credentials; // Serialize the metadata and convert it to an XElement MetadataSerializer serializer = new MetadataSerializer(); MemoryStream stream = new MemoryStream(); serializer.WriteMetadata(stream, entity); stream.Flush(); return stream.ToArray(); }