/// <summary> /// /// </summary> /// <param name="rawData">Token URL encoded.</param> /// <param name="credentials">HMAC key.</param> public SimpleWebToken(String rawData, SigningCredentials credentials) { if (null == rawData) throw new ArgumentNullException("rawData"); if (null == credentials) throw new ArgumentNullException("credentials"); this.id = SecurityUniqueId.Create().Value; this.Values = GetNameValues(rawData); this.SigningCredentials = credentials; // Split hash from data String[] rawParts = rawData.Split(new String[] { "&HMACSHA256=" }, StringSplitOptions.RemoveEmptyEntries); if (2 != rawParts.Length) throw new SecurityTokenException("Malformed Token"); this.rawData = rawParts[0]; this.hash = HttpUtility.UrlDecode(rawParts[1]); // Calculate token expiration value String expiresText = Values[WrapConstants.SimpleWebTokenParameters.ExpiresOn]; UInt64 expiresValue; if (null == expires || false == UInt64.TryParse(expiresText, out expiresValue)) throw new SecurityTokenException("Malformed Token"); this.expires = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(expiresValue); }
private static void Main(string[] args) { var key = Convert.FromBase64String(SymmetricKey); var credentials = new SigningCredentials( new InMemorySymmetricSecurityKey(key), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bhogg"), new Claim(ClaimTypes.GivenName, "Boss"), new Claim(ClaimTypes.Surname, "Hogg"), new Claim(ClaimTypes.Role, "Manager"), new Claim(ClaimTypes.Role, "SeniorWorker"), }), TokenIssuerName = "corp", AppliesToAddress = "http://www.example.com", SigningCredentials = credentials, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddYears(10)) }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); Console.WriteLine(tokenString); Debug.WriteLine(tokenString); Console.ReadLine(); }
/// <summary> /// Creates the json web token. /// </summary> /// <param name="token">The token.</param> /// <param name="credentials">The credentials.</param> /// <returns></returns> protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials) { var jwt = new JwtSecurityToken( token.Issuer, token.Audience, token.Claims, DateTimeHelper.UtcNow, DateTimeHelper.UtcNow.AddSeconds(token.Lifetime), credentials); // amr is an array - if there is only a single value turn it into an array if (jwt.Payload.ContainsKey("amr")) { var amrValue = jwt.Payload["amr"] as string; if (amrValue != null) { jwt.Payload["amr"] = new string[] { amrValue }; } } var x509credential = credentials as X509SigningCredentials; if (x509credential != null) { jwt.Header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash())); } var handler = new JwtSecurityTokenHandler(); return handler.WriteToken(jwt); }
// The Method is used to generate token for user public string GenerateTokenForUser(string userName, string userId) { var now = DateTime.UtcNow; var signingCredentials = new System.IdentityModel.Tokens.SigningCredentials(signingKey, System.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature, System.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest); var claimsIdentity = new ClaimsIdentity(new List <Claim>() { new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.NameIdentifier, userId.ToString()), }, "Custom"); var securityTokenDescriptor = new System.IdentityModel.Tokens.SecurityTokenDescriptor() { AppliesToAddress = "http://www.example.com", TokenIssuerName = "self", Subject = claimsIdentity, SigningCredentials = signingCredentials, Lifetime = new Lifetime(now, now.AddYears(1)), }; var tokenHandler = new JwtSecurityTokenHandler(); var plainToken = tokenHandler.CreateToken(securityTokenDescriptor); var signedAndEncodedToken = tokenHandler.WriteToken(plainToken); return(signedAndEncodedToken); }
/// <summary> /// Creates the json web token. /// </summary> /// <param name="token">The token.</param> /// <param name="credentials">The credentials.</param> /// <returns>The signed JWT</returns> protected virtual async Task<string> CreateJsonWebToken(Token token, SigningCredentials credentials) { var header = CreateHeader(token, credentials); var payload = CreatePayload(token); return await SignAsync(new JwtSecurityToken(header, payload)); }
public TokenController( IOptions<OAuthBearerAuthenticationOptions> bearerOptions, SigningCredentials signingCredentials) { _bearerOptions = bearerOptions.Options; _signingCredentials = signingCredentials; }
public JwtAuthenticationOwinMiddlewareTests() { var signingCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(Convert.FromBase64String(Key)), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new [] { new Claim("sub", "Alice"), new Claim("email", "*****@*****.**"), }), TokenIssuerName = Issuer, AppliesToAddress = Audience, Lifetime = new Lifetime(now, now.AddMinutes(LifetimeInMinutes)), SigningCredentials = signingCredentials, }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); _tokenString = tokenHandler.WriteToken(token); }
public void End2End_OpenIdConnect() { SigningCredentials rsaSigningCredentials = new SigningCredentials( KeyingMaterial.RsaSecurityKey_Private2048, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha256Digest, new SecurityKeyIdentifier(new NamedKeySecurityKeyIdentifierClause("kid", "NGTFvdK-fythEuLwjpwAJOM9n-A")) ); //"<RSAKeyValue><Modulus>rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>" RSA rsa = KeyingMaterial.RsaSecurityKey_2048.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha1Signature, false) as RSA; OpenIdConnectConfiguration configuration = OpenIdConnectConfigurationRetriever.GetAsync(OpenIdConfigData.OpenIdConnectMetadataFile, CancellationToken.None).Result; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwt = tokenHandler.CreateToken( configuration.Issuer, IdentityUtilities.DefaultAudience, IdentityUtilities.DefaultClaimsIdentity, DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1), rsaSigningCredentials ); TokenValidationParameters validationParameters = new TokenValidationParameters { IssuerSigningTokens = configuration.SigningTokens, ValidAudience = IdentityUtilities.DefaultAudience, ValidIssuer = configuration.Issuer, }; SecurityToken securityToken = null; tokenHandler.ValidateToken(jwt.RawData, validationParameters, out securityToken); }
/// <summary> /// Creates a SAML Token with the input parameters /// </summary> /// <param name="stsName">Name of the STS issuing the SAML Token</param> /// <param name="proofToken">Associated Proof Token</param> /// <param name="issuerToken">Associated Issuer Token</param> /// <param name="proofKeyEncryptionToken">Token to encrypt the proof key with</param> /// <param name="samlConditions">The Saml Conditions to be used in the construction of the SAML Token</param> /// <param name="samlAttributes">The Saml Attributes to be used in the construction of the SAML Token</param> /// <returns>A SAML Token</returns> public static SamlSecurityToken CreateSamlToken(string stsName, BinarySecretSecurityToken proofToken, SecurityToken issuerToken, SecurityToken proofKeyEncryptionToken, SamlConditions samlConditions, IEnumerable<SamlAttribute> samlAttributes) { // Create a security token reference to the issuer certificate SecurityKeyIdentifierClause skic = issuerToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>(); SecurityKeyIdentifier issuerKeyIdentifier = new SecurityKeyIdentifier(skic); // Create an encrypted key clause containing the encrypted proof key byte[] wrappedKey = proofKeyEncryptionToken.SecurityKeys[0].EncryptKey(SecurityAlgorithms.RsaOaepKeyWrap, proofToken.GetKeyBytes()); SecurityKeyIdentifierClause encryptingTokenClause = proofKeyEncryptionToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>(); EncryptedKeyIdentifierClause encryptedKeyClause = new EncryptedKeyIdentifierClause(wrappedKey, SecurityAlgorithms.RsaOaepKeyWrap, new SecurityKeyIdentifier(encryptingTokenClause) ); SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(encryptedKeyClause); // Create a comfirmationMethod for HolderOfKey List<string> confirmationMethods = new List<string>(1); confirmationMethods.Add(SamlConstants.HolderOfKey); // Create a SamlSubject with proof key and confirmation method from above SamlSubject samlSubject = new SamlSubject(null, null, null, confirmationMethods, null, proofKeyIdentifier); // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the SamlSubject from above SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes); // Put the SamlAttributeStatement into a list of SamlStatements List<SamlStatement> samlSubjectStatements = new List<SamlStatement>(); samlSubjectStatements.Add(samlAttributeStatement); // Create a SigningCredentials instance from the key associated with the issuerToken. SigningCredentials signingCredentials = new SigningCredentials(issuerToken.SecurityKeys[0], SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, issuerKeyIdentifier); // Create a SamlAssertion from the list of SamlStatements created above and the passed in // SamlConditions. SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), stsName, DateTime.UtcNow, samlConditions, new SamlAdvice(), samlSubjectStatements ); // Set the SigningCredentials for the SamlAssertion samlAssertion.SigningCredentials = signingCredentials; // Create a SamlSecurityToken from the SamlAssertion and return it return new SamlSecurityToken(samlAssertion); }
public AuthController(ISessionProvider<AefSession> sessionProvider, IOptions<JwtBearerOptions> bearerOptions, SigningCredentials signingCredentials, IAccountManager accountManager) :base(sessionProvider) { this.m_BearerOptions = bearerOptions.Value; this.m_SigningCredentials = signingCredentials; this.m_AccountManager = accountManager; }
public AuthController(ISessionScopeFactory sessionScopeFactory, IOptions<OAuthBearerAuthenticationOptions> bearerOptions, SigningCredentials signingCredentials, IAccountManager accountManager) :base(sessionScopeFactory) { //this.m_BearerOptions = bearerOptions.Options; this.m_SigningCredentials = signingCredentials; this.m_AccountManager = accountManager; this.m_SessionScopeFactory = sessionScopeFactory; }
protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials) { var jwt = new JwtSecurityToken( token.Issuer, token.Audience, token.Claims, new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(token.Lifetime)), credentials); var handler = new JwtSecurityTokenHandler(); return handler.WriteToken(jwt); }
/// <summary> /// Initializes an instance of <see cref="EnvelopedSignatureWriter"/>. The returned writer can be directly used /// to write the envelope. The signature will be automatically generated when /// the envelope is completed. /// </summary> /// <param name="innerWriter">Writer to wrap/</param> /// <param name="signingCredentials">SigningCredentials to be used to generate the signature.</param> /// <param name="referenceId">The reference Id of the envelope.</param> /// <param name="securityTokenSerializer">SecurityTokenSerializer to serialize the signature KeyInfo.</param> /// <exception cref="ArgumentNullException">One of he input parameter is null.</exception> /// <exception cref="ArgumentException">The string 'referenceId' is either null or empty.</exception> public EnvelopedSignatureWriter(XmlWriter innerWriter, SigningCredentials signingCredentials, string referenceId, SecurityTokenSerializer securityTokenSerializer) { if (innerWriter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerWriter"); } if (signingCredentials == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("signingCredentials"); } if (string.IsNullOrEmpty(referenceId)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID0006), "referenceId")); } if (securityTokenSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer"); } // Remember the user's writer here. We need to finally write out the signed XML // into this writer. _dictionaryManager = new DictionaryManager(); _innerWriter = innerWriter; _signingCreds = signingCredentials; _referenceId = referenceId; _tokenSerializer = securityTokenSerializer; _signatureFragment = new MemoryStream(); _endFragment = new MemoryStream(); _writerStream = new MemoryStream(); XmlDictionaryWriter effectiveWriter = XmlDictionaryWriter.CreateTextWriter(_writerStream, Encoding.UTF8, false); // Initialize the base writer to the newly created writer. The user should write the XML // to this. base.InitializeInnerWriter(effectiveWriter); _hashAlgorithm = CryptoHelper.CreateHashAlgorithm(_signingCreds.DigestAlgorithm); _hashStream = new HashStream(_hashAlgorithm); base.InnerWriter.StartCanonicalization(_hashStream, false, null); // // Add tracing for the un-canonicalized bytes // if (DiagnosticUtility.ShouldTraceVerbose) { _preCanonicalTracingStream = new MemoryStream(); base.InitializeTracingWriter(new XmlTextWriter(_preCanonicalTracingStream, Encoding.UTF8)); } }
private string CreateToken(ClaimsIdentity identity, SigningCredentials signingCredentials) { var tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = Audience, Subject = identity, TokenIssuerName = TokenIssuerName, SigningCredentials = signingCredentials, }; var handler = new JwtSecurityTokenHandler(); var token = handler.CreateToken(tokenDescriptor); return handler.WriteToken(token); }
/// <summary> /// Constructor for JWT authetication /// </summary> /// <param name="boxConfig">Config contains information about client id, client secret, enterprise id, private key, private key password, public key id </param> public BoxJWTAuth(IBoxConfig boxConfig) { this.boxConfig = boxConfig; var pwf = new PEMPasswordFinder(this.boxConfig.JWTPrivateKeyPassword); AsymmetricCipherKeyPair key; using (var reader = new StringReader(this.boxConfig.JWTPrivateKey)) { key = (AsymmetricCipherKeyPair)new PemReader(reader, pwf).ReadObject(); } var rsa = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)key.Private); this.credentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); }
public void Can_create_and_consume_jwt_tokens() { const string issuer = "http://issuer.webapibook.net"; const string audience = "*****@*****.**"; const int lifetimeInMinutes = 5; var tokenHandler = new JwtSecurityTokenHandler(); var symmetricKey = GetRandomBytes(256 / 8); var signingCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(symmetricKey), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var now = DateTime.UtcNow; var claims = new[] { new Claim("sub", "*****@*****.**"), new Claim("email", "*****@*****.**"), new Claim("name", "Alice"), }; var token = new JwtSecurityToken(issuer, audience, claims, new Lifetime(now, now.AddMinutes(lifetimeInMinutes)), signingCredentials); var tokenString = tokenHandler.WriteToken(token); var parts = tokenString.Split('.'); Assert.Equal(3, parts.Length); var validationParameters = new TokenValidationParameters() { AllowedAudience = audience, SigningToken = new BinarySecretSecurityToken(symmetricKey), ValidIssuer = issuer, }; tokenHandler.NameClaimType = ClaimTypes.NameIdentifier; var principal = tokenHandler.ValidateToken(tokenString, validationParameters); var identity = principal.Identities.First(); Assert.Equal("*****@*****.**", identity.Name); Assert.Equal("*****@*****.**", identity.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value); Assert.Equal("*****@*****.**", identity.Claims.First(c => c.Type == ClaimTypes.Email).Value); Assert.Equal("Alice", identity.Claims.First(c => c.Type == "name").Value); Assert.Equal(issuer, identity.Claims.First().Issuer); }
public static String GenerateToken(this JwtSecurityTokenHandler tokenHandler, JwtBearerOptions options, SigningCredentials signingCredentials, ClaimsIdentity identity) { if (tokenHandler == null) throw new ArgumentNullException(nameof(tokenHandler)); if (options == null) throw new ArgumentNullException(nameof(options)); if (signingCredentials == null) throw new ArgumentNullException(nameof(signingCredentials)); if (identity == null) throw new ArgumentNullException(nameof(identity)); var token = tokenHandler.CreateToken( issuer: options.TokenValidationParameters.ValidIssuer, audience: options.TokenValidationParameters.ValidAudience, signingCredentials: signingCredentials, subject: identity); return tokenHandler.WriteToken(token); }
public BoxJWTHelper(string enterpriseId, string clientId, string clientSecret, string privateKey, string privateKeyPassword) { this.enterpriseId = enterpriseId; this.clientId = clientId; this.clientSecret = clientSecret; var pwf = new PEMPasswordFinder(privateKeyPassword); AsymmetricCipherKeyPair key; using (var reader = new StringReader(privateKey)) { key = (AsymmetricCipherKeyPair)new PemReader(reader, pwf).ReadObject(); } var rsa = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)key.Private); this.credentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); }
public STSService(SecurityTokenServiceConfiguration configuration) : base(configuration) { _signingCredentials = new X509SigningCredentials( CertificateUtility.GetCertificateByThumbprint( StoreLocation.LocalMachine, StoreName.My, WebConfigurationManager.AppSettings["SigningCertificateThumbprint"].ToString())); if (!string.IsNullOrWhiteSpace(WebConfigurationManager.AppSettings["EncryptingCertificateName"].ToString())) { _encryptingCredentials = new X509EncryptingCredentials( CertificateUtility.GetCertificateByThumbprint( StoreLocation.LocalMachine, StoreName.My, WebConfigurationManager.AppSettings["EncryptingCertificateName"].ToString())); } }
public static Wrapper Sign(List<Claim> claims, DateTime expiresIn, SigningCredentials credentials, string issuer, string audience) { /* System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create(); byte[] data = new byte[64]; rng.GetBytes(data); BitConverter.ToString(data).Replace("-", ""); */ var notBefore = DateTime.Now; //Not Before Date Expires var token = new JwtSecurityToken(issuer, audience, claims, notBefore, expiresIn, credentials); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return new Wrapper(expiresIn, "Bearer", jwt); }
public JwtTokenGenerator() { var random = new byte[64]; using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(random); //Use a in memory random generated symetrickey so when the service is restarted, all token generated before restart are invalidated var symetricSecurityKey = new InMemorySymmetricSecurityKey(Encoding.ASCII.GetBytes("90htwn5AtMMiKBfRsf8BPlnK0uAmyQejcoV0rVWTatLpEZfZhVIjr3l78N28dAB4")); this.credentials = new SigningCredentials(symetricSecurityKey, JwtTokenGenerator.SignatureAlgorithm, JwtTokenGenerator.DigestAlgorithm); this.validationParameters = new TokenValidationParameters { IssuerSigningKey = symetricSecurityKey, ValidateAudience = false, ValidIssuer = JwtTokenGenerator.TokenIssuer }; }
public void Security_SymmetricKeyTokenVerificationFact() { var issuer = "http://katanatesting.com/"; var sentIdentity = new ClaimsIdentity("CustomJwt", "MyNameClaimType", "MyRoleClaimType"); sentIdentity.AddClaims(new Claim[] { new Claim("MyNameClaimType", "TestUser"), new Claim("MyRoleClaimType", "Administrator") }); for (int i = 0; i < 5; i++) { sentIdentity.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString())); } var authProperties = new AuthenticationProperties(); var sentTicket = new AuthenticationTicket(sentIdentity, authProperties); var signingAlgorithm = new AesManaged(); var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(signingAlgorithm.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); var tokenValidationParameters = new TokenValidationParameters() { ValidAudience = issuer, SaveSigninToken = true, AuthenticationType = sentIdentity.AuthenticationType }; var formatter = new JwtFormat(tokenValidationParameters, new SymmetricKeyIssuerSecurityTokenProvider(issuer, signingAlgorithm.Key)); formatter.TokenHandler = new JwtSecurityTokenHandler(); var protectedtext = SecurityUtils.CreateJwtToken(sentTicket, issuer, signingCredentials); //Receive part var receivedTicket = formatter.Unprotect(protectedtext); var receivedClaims = receivedTicket.Identity.Claims; Assert.Equal<string>("CustomJwt", receivedTicket.Identity.AuthenticationType); Assert.Equal<string>(ClaimsIdentity.DefaultNameClaimType, receivedTicket.Identity.NameClaimType); Assert.Equal<string>(ClaimsIdentity.DefaultRoleClaimType, receivedTicket.Identity.RoleClaimType); Assert.NotNull(receivedTicket.Identity.BootstrapContext); Assert.NotNull(((BootstrapContext)receivedTicket.Identity.BootstrapContext).Token); Assert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "iss").FirstOrDefault().Value); Assert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "aud").FirstOrDefault().Value); Assert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "exp").FirstOrDefault().Value); for (int i = 0; i < 5; i++) { sentIdentity.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString())); Assert.Equal<string>(i.ToString(), receivedClaims.Where<Claim>(claim => claim.Type == "ClaimId" + i.ToString()).FirstOrDefault().Value); } Assert.Equal<string>("TestUser", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType).FirstOrDefault().Value); Assert.Equal<string>("Administrator", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdentity.DefaultRoleClaimType).FirstOrDefault().Value); Assert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "iat").FirstOrDefault().Value); Assert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "jti").FirstOrDefault().Value); }
public RequestDetailsScope(RequestDetails details, SigningCredentials signingCredentials, bool requireEncryption) : base(details.Realm.Uri.AbsoluteUri, signingCredentials) { RequestDetails = details; if (RequestDetails.UsesEncryption) { EncryptingCredentials = new X509EncryptingCredentials(details.EncryptingCertificate); } if (RequestDetails.TokenType == SimpleWebToken.OasisTokenProfile) { SigningCredentials = new SymmetricSigningCredentials(details.RelyingPartyRegistration.SymmetricSigningKey); } ReplyToAddress = RequestDetails.ReplyToAddress.AbsoluteUri; TokenEncryptionRequired = requireEncryption; }
private static SigningCredentials GenerateSigningCredentials() { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var x509Certificate2 = store.Certificates.Find(X509FindType.FindByThumbprint, "4443BE13F1B67C4D2733FFBF100E4F114B08FFBF", false).OfType<X509Certificate2>().FirstOrDefault(); // Both signatures work var signingToken = new X509AsymmetricSecurityKey(x509Certificate2); var securityKeyIdentifier1 = new SecurityKeyIdentifier(new X509RawDataKeyIdentifierClause(x509Certificate2)); var signingCredentials1 = new SigningCredentials(signingToken, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest, securityKeyIdentifier1); //RSACryptoServiceProvider rsa = x509Certificate2.PrivateKey as RSACryptoServiceProvider; //RsaSecurityKey rsaKey = new RsaSecurityKey(rsa); //X509RawDataKeyIdentifierClause x509RawClause = new X509RawDataKeyIdentifierClause(x509Certificate2); //SecurityKeyIdentifier securityKeyIdentifier2 = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { x509RawClause }); //SigningCredentials signingCredentials2 = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, securityKeyIdentifier2); return signingCredentials1; }
protected virtual JwtSecurityToken CreateTokenFromClaims(IEnumerable<Claim> claims, string secretKey, string audience, string issuer) { var signingKey = this.GetSigningKey(secretKey); var signingToken = new BinarySecretSecurityToken(signingKey); var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(signingToken.GetKeyBytes()), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = audience, TokenIssuerName = issuer, SigningCredentials = signingCredentials, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromDays(1)), Subject = new ClaimsIdentity(claims), }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken; return token; }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = StoneCastle.Security.Commons.Constants.CONFIGURATION_AUDIENCE_ID; string symmetricKeyAsBase64 = StoneCastle.Security.Commons.Constants.CONFIGURATION_AUDIENCE_SECRET; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); //var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray); //var securityKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(keyByteArray); //var signingCredentials = new System.IdentityModel.Tokens.SigningCredentials(securityKey, // Microsoft.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256Signature, // System.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest); //var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, // Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); var signingCredentials = new System.IdentityModel.Tokens.SigningCredentials( new InMemorySymmetricSecurityKey(keyByteArray), SignatureAlgorithm, DigestAlgorithm); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; //var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials); //var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
/// <summary> /// Creates the json web token. /// </summary> /// <param name="token">The token.</param> /// <param name="credentials">The credentials.</param> /// <returns></returns> protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials) { var jwt = new JwtSecurityToken( token.Issuer, token.Audience, token.Claims, DateTimeHelper.UtcNow, DateTimeHelper.UtcNow.AddSeconds(token.Lifetime), credentials); var x509credential = credentials as X509SigningCredentials; if (x509credential != null) { jwt.Header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash())); } var handler = new JwtSecurityTokenHandler(); return handler.WriteToken(jwt); }
public static JWTSecurityToken GenerateJwtToken(string issuer, string subject, string audience, DateTime expires, byte[] signature) { DateTime issuedAt = DateTime.UtcNow; // Create signing credentials for the signed JWT. // This object is used to cryptographically sign the JWT by the issuer. SigningCredentials signingCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(signature), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); // Create a simple JWT claim set IList<Claim> claims = new List<Claim>() { new Claim("sub", subject), new Claim("iat", ToUnixTime(issuedAt).ToString()) }; // Create a JWT with signing credentials and lifetime of 12 hours JWTSecurityToken jwt = new JWTSecurityToken(issuer, audience, claims, signingCredentials, issuedAt, expires); return jwt; }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } var issuer = "localhost"; var audience = "all"; var key = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]); var now = DateTime.UtcNow; var expires = now.AddMinutes(_options.AccessTokenExpireTimeSpan.TotalMinutes); var signingCredentials = new System.IdentityModel.Tokens.SigningCredentials( new InMemorySymmetricSecurityKey(key), SignatureAlgorithm, DigestAlgorithm); var token = new JwtSecurityToken(issuer, audience, data.Identity.Claims, now, expires, signingCredentials); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public RequestDetailsScope(RequestDetails details, SigningCredentials signingCredentials, bool requireEncryption) : base(details.Realm.Uri.AbsoluteUri, signingCredentials) { RequestDetails = details; if (RequestDetails.UsesEncryption) { EncryptingCredentials = new X509EncryptingCredentials(details.EncryptingCertificate); } if (RequestDetails.TokenType == TokenTypes.SimpleWebToken || RequestDetails.TokenType == TokenTypes.JsonWebToken) { if (details.RelyingPartyRegistration.SymmetricSigningKey != null && details.RelyingPartyRegistration.SymmetricSigningKey.Length > 0) { SigningCredentials = new HmacSigningCredentials(details.RelyingPartyRegistration.SymmetricSigningKey); } } ReplyToAddress = RequestDetails.ReplyToAddress.AbsoluteUri; TokenEncryptionRequired = requireEncryption; }
public static string CreateJwtToken(AuthenticationTicket data, string issuer, SigningCredentials signingCredentials) { string audience = issuer; // As JWT doesn't have a mechanism of passing metadata about what claim should be the name/subject the JWT handler // users the default Name claim type. If the identity has another claim type as the name type we need to // switch it to the DefaultNameClaimType. var identity = new ClaimsIdentity(data.Identity); if (identity.NameClaimType != ClaimsIdentity.DefaultNameClaimType && !string.IsNullOrWhiteSpace(identity.Name)) { identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, identity.Name)); identity.RemoveClaim(identity.Claims.First(c => c.Type == identity.NameClaimType)); } // And now do the same for roles. List<Claim> roleClaims = identity.Claims.Where(c => c.Type == identity.RoleClaimType).ToList(); if (identity.RoleClaimType != ClaimsIdentity.DefaultRoleClaimType && roleClaims.Any()) { foreach (var roleClaim in roleClaims) { identity.RemoveClaim(roleClaim); identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, roleClaim.Value, roleClaim.ValueType, roleClaim.Issuer, roleClaim.OriginalIssuer)); } } identity.AddClaims(new[] { new Claim("iat", GetEpocTimeStamp()), new Claim("jti", Guid.NewGuid().ToString("N")) }); Lifetime lifetime = new Lifetime(null, null); if (data.Properties.IssuedUtc != null || data.Properties.ExpiresUtc != null) { lifetime = new Lifetime(data.Properties.IssuedUtc != null ? (DateTime?)((DateTimeOffset)data.Properties.IssuedUtc).UtcDateTime : null, data.Properties.ExpiresUtc != null ? (DateTime?)((DateTimeOffset)data.Properties.ExpiresUtc).UtcDateTime : null); } var handler = new JwtSecurityTokenHandler(); return handler.CreateToken(issuer, audience, identity, lifetime.Created, lifetime.Expires, signingCredentials).RawData; }
public static IServiceCollection ConfigureOAuthBearerAuthenticationOptions(this IServiceCollection services, String rsaKeyPath) { if (services == null) throw new ArgumentNullException(nameof(services)); //Configure OAuthBearerAuthenticationOptions RsaSecurityKey key = LoadRsaSecurityKey(rsaKeyPath); services.Configure<JwtBearerOptions>(options => { options.TokenValidationParameters.ValidIssuer = TokenIssuer; options.TokenValidationParameters.ValidAudience = TokenAudience; options.TokenValidationParameters.IssuerSigningKey = key; options.AutomaticAuthenticate = true; }); //Register SigningCredentials used by AuthController var signingCredentials = new SigningCredentials(key,SecurityAlgorithms.RsaSha256Signature); services.AddInstance(signingCredentials); return services; }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } var config = AppConfiguration.Config; var issuer = config.JwtIssuer; var audience = config.JwtAudience; var key = Convert.FromBase64String(config.JwtKey); var now = DateTime.UtcNow; var expires = now.AddMinutes(_options.AccessTokenExpireTimeSpan.TotalMinutes); var signingCredentials = new System.IdentityModel.Tokens.SigningCredentials( new InMemorySymmetricSecurityKey(key), SignatureAlgorithm, DigestAlgorithm); var token = new JwtSecurityToken(issuer, audience, data.Identity.Claims, now, expires, signingCredentials); return(new JwtSecurityTokenHandler().WriteToken(token)); }
/// <summary> /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class specifying optional parameters. /// </summary> /// <param name="issuer">if this value is not null, a { iss, 'issuer' } claim will be added.</param> /// <param name="audience">if this value is not null, a { aud, 'audience' } claim will be added</param> /// <param name="claims">if this value is not null then for each <see cref="Claim"/> a { 'Claim.Type', 'Claim.Value' } is added. If duplicate claims are found then a { 'Claim.Type', List<object> } will be created to contain the duplicate values.</param> /// <param name="expires">if expires.HasValue a { exp, 'value' } claim is added.</param> /// <param name="notBefore">if notbefore.HasValue a { nbf, 'value' } claim is added.</param> /// <param name="signingCredentials">The <see cref="SigningCredentials"/> that will be used to sign the <see cref="JwtSecurityToken"/>. See <see cref="JwtHeader(SigningCredentials)"/> for details pertaining to the Header Parameter(s).</param> /// <exception cref="ArgumentException">if 'expires' <= 'notbefore'.</exception> public JwtSecurityToken(string issuer = null, string audience = null, IEnumerable <Claim> claims = null, DateTime?notBefore = null, DateTime?expires = null, SigningCredentials signingCredentials = null) { if (expires.HasValue && notBefore.HasValue) { if (notBefore >= expires) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10401, expires.Value, notBefore.Value)); } } this.payload = new JwtPayload(issuer: issuer, audience: audience, claims: claims, notBefore: notBefore, expires: expires); this.header = new JwtHeader(signingCredentials); }
private string CreateJwt(string userId, string role) { var key = Convert.FromBase64String(SymmetricKey); var credentials = new SigningCredentials( new InMemorySymmetricSecurityKey(key), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var expiration = DateTime.UtcNow.AddMinutes(20).ToLongTimeString(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId), new Claim(ClaimTypes.Role, role), new Claim("exp", expiration) }), TokenIssuerName = Issuer, AppliesToAddress = Audience, SigningCredentials = credentials }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return tokenString; }