public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = ConfigurationManager.AppSettings["audienceId"]; string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["audienceSecret"]; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new HmacSigningCredentials(keyByteArray); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; var token = new System.IdentityModel.Tokens.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey); var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
public static string MakeToken(string secret, string user) { var securityKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(Encoding.Default.GetBytes(secret)); System.IdentityModel.Tokens.SigningCredentials signingCredentials = new System.IdentityModel.Tokens.SigningCredentials( securityKey, "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); byte[] randomNonce = new Byte[32]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomNonce); List <Claim> claims = new List <Claim>() { new Claim("user", user), new Claim("nonce", Convert.ToBase64String(randomNonce)), }; var jwtSecurityToken = new System.IdentityModel.Tokens.JwtSecurityToken( issuer, audience, claims, DateTime.Now, DateTime.Now.AddHours(1), signingCredentials ); var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler(); string tokenString = handler.WriteToken(jwtSecurityToken); return(tokenString); }