public void CreateAndValidateTokens_MultipleX5C() { List<string> errors = new List<string>(); var handler = new JwtSecurityTokenHandler(); var payload = new JwtPayload(); var header = new JwtHeader(); payload.AddClaims(ClaimSets.MultipleAudiences(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer)); List<string> x5cs = new List<string> { "x5c1", "x5c2" }; header.Add(JwtHeaderParameterNames.X5c, x5cs); var jwtToken = new JwtSecurityToken(header, payload); var jwt = handler.WriteToken(jwtToken); var validationParameters = new TokenValidationParameters { RequireExpirationTime = false, RequireSignedTokens = false, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, }; SecurityToken validatedSecurityToken = null; var cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken); JwtSecurityToken validatedJwt = validatedSecurityToken as JwtSecurityToken; object x5csInHeader = validatedJwt.Header[JwtHeaderParameterNames.X5c]; if (x5csInHeader == null) { errors.Add("1: validatedJwt.Header[JwtHeaderParameterNames.X5c]"); } else { var list = x5csInHeader as IEnumerable<object>; if ( list == null ) { errors.Add("2: var list = x5csInHeader as IEnumerable<object>; is NULL."); } int num = 0; foreach(var str in list) { num++; if (!(str is string)) { errors.Add("3: str is not string, is:" + str.ToString()); } } if (num != x5cs.Count) { errors.Add("4: num != x5cs.Count. num: " + num.ToString() + "x5cs.Count: " + x5cs.Count.ToString()); } } // make sure we can still validate with existing logic. header = new JwtHeader(KeyingMaterial.DefaultAsymmetricSigningCreds_2048_RsaSha2_Sha2); header.Add(JwtHeaderParameterNames.X5c, x5cs); jwtToken = new JwtSecurityToken(header, payload); jwt = handler.WriteToken(jwtToken); validationParameters.IssuerSigningToken = KeyingMaterial.DefaultAsymmetricX509Token_2048; validationParameters.RequireSignedTokens = true; validatedSecurityToken = null; cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken); TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors); }
/// <summary> /// Decodes the string into the header, payload and signature /// </summary> /// <param name="jwtEncodedString">Base64Url encoded string.</param> internal void Decode(string jwtEncodedString) { string[] tokenParts = jwtEncodedString.Split(new char[] { '.' }, 4); if (tokenParts.Length != 3) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10709, "jwtEncodedString", jwtEncodedString)); } try { this.header = JwtHeader.Base64UrlDeserialize(tokenParts[0]); // if present, "typ" should be set to "JWT" or "http://openid.net/specs/jwt/1.0" string type = this.header.Typ; if (type != null) { if (!(StringComparer.Ordinal.Equals(type, JwtConstants.HeaderType) || StringComparer.Ordinal.Equals(type, JwtConstants.HeaderTypeAlt))) { throw new SecurityTokenException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10702, JwtConstants.HeaderType, JwtConstants.HeaderTypeAlt, type)); } } } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "header", tokenParts[0], jwtEncodedString), ex); } try { this.payload = JwtPayload.Base64UrlDeserialize(tokenParts[1]); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "payload", tokenParts[1], jwtEncodedString), ex); } // ensure signature is well-formed, GitIssue 103 if (!string.IsNullOrEmpty(tokenParts[2])) { try { Base64UrlEncoder.Decode(tokenParts[2]); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "signature", tokenParts[1], jwtEncodedString), ex); } } this.rawData = jwtEncodedString; this.rawHeader = tokenParts[0]; this.rawPayload = tokenParts[1]; this.rawSignature = tokenParts[2]; }
/// <summary> /// Creates the JWT header /// </summary> /// <param name="token">The token.</param> /// <param name="credential">The credentials.</param> /// <returns>The JWT header</returns> protected virtual Task<JwtHeader> CreateHeaderAsync(Token token, SecurityKey key) { JwtHeader header = null; header = new JwtHeader(new SigningCredentials(key, "RS256")); return Task.FromResult(header); }
/// <summary> /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class where the <see cref="JwtHeader"/> contains the crypto algorithms applied to the encoded <see cref="JwtHeader"/> and <see cref="JwtPayload"/>. The jwtEncodedString is the result of those operations. /// </summary> /// <param name="header">Contains JSON objects representing the cryptographic operations applied to the JWT and optionally any additional properties of the JWT</param> /// <param name="payload">Contains JSON objects representing the claims contained in the JWT. Each claim is a JSON object of the form { Name, Value }</param> /// <param name="rawHeader">base64urlencoded JwtHeader</param> /// <param name="rawPayload">base64urlencoded JwtPayload</param> /// <param name="rawSignature">base64urlencoded JwtSignature</param> /// <exception cref="ArgumentNullException">'header' is null.</exception> /// <exception cref="ArgumentNullException">'payload' is null.</exception> /// <exception cref="ArgumentNullException">'rawSignature' is null.</exception> /// <exception cref="ArgumentException">'rawHeader' or 'rawPayload' is null or whitespace.</exception> public JwtSecurityToken(JwtHeader header, JwtPayload payload, string rawHeader, string rawPayload, string rawSignature) { if (header == null) { throw new ArgumentNullException("header"); } if (payload == null) { throw new ArgumentNullException("payload"); } if (rawSignature == null) { throw new ArgumentNullException("rawSignature"); } if (string.IsNullOrWhiteSpace(rawHeader)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "rawHeader")); } if (string.IsNullOrWhiteSpace(rawPayload)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "rawPayload")); } this.header = header; this.payload = payload; this.rawData = string.Concat(rawHeader, ".", rawPayload, ".", rawSignature); this.rawHeader = rawHeader; this.rawPayload = rawPayload; this.rawSignature = rawSignature; }
private void InitializeJwtParameters() { _jwtHeader = new JwtHeader(_signingCredentials); Parameters = new TokenValidationParameters { ValidateAudience = false, ValidIssuer = "https://portal.fpt.com.vn", IssuerSigningKey = _issuerSigningKey }; }
public AccountService(IOptions <JwtOptions> jwtOptions, ILogger <AccountService> logger, ProfanityServiceDbContext context, IMapper mapper) { _logger = logger; _jwtOptions = jwtOptions.Value; _securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecretKey)); _signingCredentials = new SigningCredentials(_securityKey, SecurityAlgorithms.HmacSha256); _jwtHeader = new JwtHeader(_signingCredentials); _context = context; _mapper = mapper; }
public void Constructors_Null_SigningCredentials() { JwtHeader jwtHeader = new JwtHeader((SigningCredentials)null); Assert.True(jwtHeader.Typ == JwtConstants.HeaderType, "jwtHeader.ContainsValue( JwtConstants.HeaderType )"); Assert.True(jwtHeader.Alg == SecurityAlgorithms.None, "jwtHeader.SignatureAlgorithm == null"); Assert.True(jwtHeader.SigningCredentials == null, "jwtHeader.SigningCredentials != null"); Assert.True(jwtHeader.Kid == null, "jwtHeader.Kid == null"); Assert.True(jwtHeader.Comparer.GetType() == StringComparer.Ordinal.GetType(), "jwtHeader.Comparer.GetType() != StringComparer.Ordinal.GetType()"); }
public void Constructors_Default() { var jwtHeader = new JwtHeader(); Assert.True(jwtHeader.Typ == null, "jwtHeader.Typ != null"); Assert.True(jwtHeader.Alg == null, "jwtHeader.Alg != null"); Assert.True(jwtHeader.SigningCredentials == null, "jwtHeader.SigningCredentials != null"); Assert.True(jwtHeader.Kid == null, "jwtHeader.Kid == null"); Assert.True(jwtHeader.Comparer.GetType() == StringComparer.Ordinal.GetType(), "jwtHeader.Comparer.GetType() != StringComparer.Ordinal.GetType()"); }
public string Generate(int id) { var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secureKey)); var credentials = new SigningCredentials(symmetricSecurityKey, algorithm: SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(credentials); var payload = new JwtPayload(issuer: id.ToString(), audience: null, claims: null, notBefore: null, expires: DateTime.Today.AddDays(1)); var securityToken = new JwtSecurityToken(header, payload); return(new JwtSecurityTokenHandler().WriteToken(securityToken)); }
private void InitializeJwtParameters() { _jwtHeader = new JwtHeader(_signingCredentials); Parameters = new TokenValidationParameters { ValidateAudience = false, ValidIssuer = _settings.Issuer, IssuerSigningKey = _issuerSigningKey }; }
public async Task <IActionResult> Login([FromBody] LoginDTO payload) { var count = await _userService.Count(); if (count <= 0) { return(NotFound()); } User user; try { user = await _userService.FindOneAsync(payload.Email); } catch (ArgumentException) { return(NotFound()); } if (!PasswordsMatch(user.Password, payload.Password)) { return(BadRequest()); } var u = new UserDTO(); Copier.CopyPropertiesTo(user, u); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetValue <string>("JwtSecret"))); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(credentials); //Some PayLoad that contain information about the customer var date = DateTime.UtcNow; var descriptor = new SecurityTokenDescriptor() { SigningCredentials = credentials, IssuedAt = date, Expires = date.AddDays(1), Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, u.Name), new Claim(ClaimTypes.NameIdentifier, u.Id.ToString()), new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(u)) }) }; var handler = new JwtSecurityTokenHandler(); // Token to String so you can use it in your client var token = handler.CreateToken(descriptor); var tokenString = handler.WriteToken(token); return(new JsonResult(new Dictionary <string, object>() { { "user", u }, { "token", tokenString } })); }
public ActionResult <User> Authenticate([FromBody] User client) { try { SqlConnection conn = new SqlConnection(SQLConnection); SqlCommand cmd = new SqlCommand("LoginUser", conn); cmd.Parameters.AddWithValue("@LoginID", client.LoginID); cmd.Parameters.AddWithValue("@PasswordID", client.PasswordID); cmd.CommandType = CommandType.StoredProcedure; conn.Open(); SqlDataReader rdr = cmd.ExecuteReader(); if (rdr.Read()) { User _user = new User { EmployeeID = rdr.GetInt32(0), LoginID = rdr.GetString(1), EmployeeType = rdr.GetByte(2), LastName = rdr.GetString(3), FirstName = rdr.GetString(4), Email = rdr.GetString(5), DepartmentName = rdr.GetString(6), PositionTitle = rdr.GetString(7), ManagerID = rdr.IsDBNull(8) ? 0 : rdr.GetInt32(8), }; //create the jwt token with key string key = "hometrustisthebestcompany"; var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(credentials); var payload = new JwtPayload { { "id", rdr.GetInt32(0).ToString() }, { "type", rdr.GetByte(2).ToString() } }; var Token = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); var tokenString = handler.WriteToken(Token); _user.jwt = tokenString; conn.Close(); return(Ok(_user)); } else { conn.Close(); return(Unauthorized()); } } catch (global::System.Exception) { return(BadRequest()); } }
public async Task <IActionResult> Create(string username, string password, string name, string surname, string Departement, string School) { if (username == (from a in _context.Users where a.Username == username select a).FirstOrDefault()?.Username) { ViewBag.error = "an user has already this username."; ViewBag.schools = (from e in _context.Schools select e).ToList(); ViewBag.departements = (from e in _context.Departements select e).ToList(); return(View()); } else { var u = new User(); u.Username = username; byte[] pass = System.Text.Encoding.ASCII.GetBytes(password); pass = new System.Security.Cryptography.SHA256Managed().ComputeHash(pass); password = System.Text.Encoding.ASCII.GetString(pass); u.Password = password; u.Name = name; u.Surname = surname; u.School = (from a in _context.Schools where a.Name == School select a).FirstOrDefault(); u.Departement = (from a in _context.Departements where a.Name == Departement && a.School == u.School select a).FirstOrDefault(); u.Ratings = new List <Rating>(); u.Admin = false; _context.Users.Add(u); _context.SaveChanges(); HttpContext.Session.SetString("username", username); HttpContext.Session.SetString("Admin", "false"); var us = (from e in _context.Users where e.Username == username select e).FirstOrDefault(); string key = "igKLnN2Rd6ygBLKNzI5VjPBVFUBdgVDw687QQFZS+1k="; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var header = new JwtHeader(credentials); var payload = new JwtPayload { { "instance", "479278d3-1b27-4b2c-9bfa-eca3af70b5f1" }, { "iss", "api_keys/d5b79396-8f8d-4292-a3fa-5d0a5dfeade1" }, { "iat", (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds }, { "exp", (Int32)(DateTime.UtcNow.Subtract(new DateTime(1969, 12, 31, 23, 30, 00))).TotalSeconds }, { "sub", "0" }, { "su", true }, }; var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); var tokenString = handler.WriteToken(secToken); _context.Users.SingleOrDefault(e => e.Username == username).Token = tokenString; _context.SaveChanges(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString); string json = JsonConvert.SerializeObject(new { id = Convert.ToString(us.Id), name = us.Username }); var response1 = await client.PostAsync("https://us1.pusherplatform.io/services/chatkit/v1/479278d3-1b27-4b2c-9bfa-eca3af70b5f1/users", new StringContent(json, Encoding.UTF8, "application/json")); var responseString1 = await response1.Content.ReadAsStringAsync(); return(RedirectToAction("Index", "Home")); } }
/// <summary> /// Generates a JWT Bearer token. /// </summary> /// <param name="principal">A ClaimsPrincipal representing the user.</param> /// <param name="notBefore">The validity start timestamp.</param> /// <param name="expires">The validity expiration timestamp.</param> /// <param name="signingCredentials">Credentials for signing the token.</param> /// <returns>A JWT token.</returns> internal static string GenerateBearer(ClaimsPrincipal principal, DateTime?notBefore = null, DateTime?expires = null, SigningCredentials signingCredentials = null) { string botlogin = Program.Settings?.BotLogin ?? ""; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtPayload payload = new JwtPayload(typeof(Program).Assembly.GetName().FullName + "/" + typeof(Program).Assembly.GetName().Version.ToString() + "/" + botlogin, botlogin, principal.Claims, notBefore, expires); JwtHeader header = new JwtHeader(signingCredentials); JwtSecurityToken token = new JwtSecurityToken(header, payload); return(tokenHandler.WriteToken(token)); }
private JwtSecurityToken BuildDeepLinkPostbackToken(JwtSecurityToken requestToken, out string returnUrl) { Claim linkSettings = requestToken.Claims.Single(x => x.Type == LtiClaims.DeepLinkingSettings); JObject settingValues = JObject.Parse(linkSettings.Value); returnUrl = (string)settingValues["deep_link_return_url"]; string data = (string)settingValues["data"]; // first - read tool's private key RSAParameters rsaParams; using (var tr = new StringReader(this.config.ToolPrivateKey)) { var pemReader = new PemReader(tr); var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair; if (keyPair == null) { throw new Exception("Could not read RSA private key"); } var privateRsaParams = keyPair.Private as RsaPrivateCrtKeyParameters; rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams); } // create security key using private key above var securityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsaParams); // note that securityKey length should be >256b so you have to make sure that your private key has a proper length var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256); // create a Token var clientAsssertionJwtTokenHeader = new JwtHeader(signingCredentials); // Some PayLoad that contain information about the caller (tool) // expected payload for access token request.. confirm with IMS guys var now = DateTime.UtcNow; var clientAsssertionJwtTokenPayload = new JwtPayload { { "iss", this.config.ClientId }, //{ "aud", this.config.PlatformTokenEndpoint }, { "aud", requestToken.Issuer }, { "exp", now.AddMinutes(5).Ticks }, // give the user 5 minutes to post the deep link? { "iat", now.Ticks }, { "jti", $"{this.config.ClientId}-{now.Ticks}" }, { "nonce", "377fdbf8cbc2f7b0799b" } }; Claim[] deepLinkResponseClaims = this.BuildResponseClaims(data); clientAsssertionJwtTokenPayload.AddClaims(deepLinkResponseClaims); var clientAsssertionJwtToken = new JwtSecurityToken(clientAsssertionJwtTokenHeader, clientAsssertionJwtTokenPayload); return(clientAsssertionJwtToken); }
public JwtManager( IOptions <JwtOptions> options, IAccessManager accessManager ) { _options = options.Value; _accessManager = accessManager; _securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey)); _signingCredentials = new SigningCredentials(_securityKey, SecurityAlgorithms.HmacSha256); _jwtHeader = new JwtHeader(_signingCredentials); }
public ClassController(ICourseService courseService, IClassService classService, IUserService userService, IFixGroupService fixGroupService, ISeminarGroupService seminarGroupService, JwtHeader header) { _courseService = courseService; _classService = classService; _userService = userService; _fixGroupService = fixGroupService; _seminarGroupService = seminarGroupService; _header = header; }
private void AddHeaderParameters(JwtHeader header, JWTOptions options) { HeaderParameters parameters = options.GetHeaderParameters(); List <string> list = parameters.GetAll(); Dictionary <string, object> map = parameters.GetMap(); foreach (string s in list) { header.Add(s.Trim(), ((string)map[s]).Trim()); } }
public void Constructors() { var header1 = new JwtHeader(); SigningCredentials signingCredentials = null; var header2 = new JwtHeader(signingCredentials); var context = new CompareContext(); IdentityComparer.AreEqual(header1, header2, context); TestUtilities.AssertFailIfErrors("JwtHeaderTests.Constructors", context.Diffs); }
private string GenerateJwtToken(string name) { var claims = new[] { new Claim(ClaimTypes.Name, name) }; var creds = new SigningCredentials(Startup.SecurityKey, SecurityAlgorithms.HmacSha256); var head = new JwtHeader(creds); var payload = new JwtPayload(claims); var tokenObj = new JwtSecurityToken(head, payload); string token = new JwtSecurityTokenHandler().WriteToken(tokenObj); return(token); }
static async Task Main(string[] args) { var clientName = "webui"; var resourcePath = "/institution/3181/customer/11212"; var requestBody = "messageBody"; var signed_payload = $"{resourcePath}.{requestBody}"; using var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(clientName)); var sig = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(signed_payload)); var sigStr = BitConverter.ToString(sig) .Replace("-", string.Empty); var jwt = new RequestJwt { Iat = 1582579659, Key = "institution:3181", Op = "CreateCustomer", Sub = "arthur", Sig = sigStr }; //var payload = jwt.AsJwtClaimsDictionary(); IdentityModelEventSource.ShowPII = true; var key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); // Sha256 throws -- because Asymmetrical? var header = new JwtHeader(credentials); var payload = new JwtPayload { { "iat", 1582579659 }, { "key", "institution:3181" }, { "op", "CreateCustomer" }, { "sub", "arthur" }, { "sig", sigStr } }; var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); var tokenString = handler.WriteToken(secToken); //throws here client.DefaultRequestHeaders.Add("token", tokenString); client.DefaultRequestHeaders.Add("client", clientName); var response = await client.PostAsync(new Uri("https://localhost:44396/weatherforecast/post"), new StringContent(requestBody)); }
public string GenerateToken(JwtPayload payload) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_securitySettings.SigningKey)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(credentials); var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); return handler.WriteToken(secToken); }
/// <summary> /// Generate Layer Identity Token /// </summary> /// <param name="userid"></param> /// <param name="nonce"></param> /// <returns></returns> public string GenerateIdentifyToken(string userid, string nonce) { var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var issueTime = DateTime.Now; var iat = (int)issueTime.Subtract(utc0).TotalSeconds; //issues time in second var exp = (int)issueTime.AddMinutes(60).Subtract(utc0).TotalSeconds; //expired time in second var jwtHeader = new JwtHeader { { "typ", "JWT" }, { "alg", "RS256" }, { "cty", "layer-eit;v=1" }, { "kid", LayerKeyId } //String - Layer Key ID used to sign the token. This is your actual Key ID }; var jwtPayload = new JwtPayload { { "iss", LayerProviderId }, //The Layer Provider ID, this is your actual provider ID { "prn", userid }, // String - Provider's internal ID for the authenticating user e.g "CgamH6kGGl" { "iat", iat }, // Integer - Time of Token Issuance in RFC 3339 seconds { "exp", exp }, // Integer - Arbitrary time of Token Expiration in RFC 3339 { "nce", nonce }//nonce from layer e.g "WxSFi3t1iu8MFBtymMBfNPUoonqXb+QO8EtrpKFdnREK44ecPTmKXglKm3KtI6S/i6/4kJam7TZStbnAW+dnsw==" }; var headerSerialized = JsonConvert.SerializeObject(jwtHeader); var headerBytes = Encoding.UTF8.GetBytes(headerSerialized); var headerEncoded = TextEncodings.Base64Url.Encode(headerBytes); var claimsetSerialized = JsonConvert.SerializeObject(jwtPayload); var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized); var claimsetEncoded = TextEncodings.Base64Url.Encode(claimsetBytes); try { var path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LayerPemFilePath"]); //use BouncyCastle for load RSA private key var sr = new StreamReader(path); var pr = new PemReader(sr); var keyPair = (AsymmetricCipherKeyPair)pr.ReadObject(); var rsaPrivate = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private); //sign data var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaPrivate); var input = String.Join(".", headerEncoded, claimsetEncoded); var inputBytes = Encoding.UTF8.GetBytes(input); var signatureBytesTemp = rsa.SignData(inputBytes, new SHA256CryptoServiceProvider()); var signatureEncoded = TextEncodings.Base64Url.Encode(signatureBytesTemp); var result = String.Join(".", headerEncoded, claimsetEncoded, signatureEncoded); return(result); } catch (Exception ex) { return(ex.Message); } }
public string Generate(int id) { var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secureKey)); var credentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(credentials); var payload = new JwtPayload(id.ToString(), null, null, null, DateTime.Today.AddDays(1)); // 1 day var securityToken = new JwtSecurityToken(header, payload); return(new JwtSecurityTokenHandler().WriteToken(securityToken)); }
public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate actionExecutionDelegate) { var headers = context.HttpContext.Request.Headers; var authHeaderValue = headers.Where(x => x.Key == "Authorization").FirstOrDefault().Value; if (authHeaderValue.Any()) { var tokenStr = authHeaderValue[0]; //Remove the Bearer text tokenStr = tokenStr.Replace("Bearer ", ""); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtSecToken = tokenHandler.ReadJwtToken(tokenStr); var username = jwtSecToken.Claims.Where(x => x.Type == ClaimTypes.NameIdentifier).FirstOrDefault(); if (username == null) { context.Result = new UnauthorizedResult(); return; } // Get the user record from back-end var userModel = await((UserdataService)_userService).GetUserByName(username.Value); // Using the secret key generate a new token // Compute jwt secret var bytes = Encoding.UTF8.GetBytes(string.Concat(_appSettings.JWTSecretKey, userModel.Secret)); SHA256Managed hash = new SHA256Managed(); byte[] jwtSecret = hash.ComputeHash(bytes); // Construct jwt header var secKey = new SymmetricSecurityKey(jwtSecret); var signingCredentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(signingCredentials); // Compare the generated token with the incoming token var generatedToken = new JwtSecurityToken(header, jwtSecToken.Payload); var newTokenString = tokenHandler.WriteToken(generatedToken); if (tokenStr == newTokenString) { await actionExecutionDelegate.Invoke(); } else { context.Result = new UnauthorizedResult(); return; } } else { context.Result = new UnauthorizedResult(); } }
public static JwtSecurityToken GenerateToken(string username) { var header = new JwtHeader { ["alg"] = "HS256" }; var payload = new JwtPayload(new[] { new Claim("username", username) }); var hmac = new HMACSHA256(Secret); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(string.Join(".", header.Base64UrlEncode(), payload.Base64UrlEncode()))); return(new JwtSecurityToken(header, payload, header.Base64UrlEncode(), payload.Base64UrlEncode(), System.IdentityModel.Tokens.Base64UrlEncoder.Encode(hash))); }
public void CompareJwtHeaders() { TestUtilities.WriteHeader($"{this}.CompareJwtHeaders", true); var context = new CompareContext($"{this}.CompareJwtHeaders"); var jwtHeader1 = new JwtHeader(Default.SymmetricSigningCredentials); var jwtHeader2 = new JwtHeader(); IdentityComparer.AreEqual(jwtHeader1, jwtHeader2, context); Assert.True(context.Diffs.Count(s => s == "Alg:") == 1); }
private static string GenerateJWTTokenString(string tokenKey, JwtPayload payload) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var header = new JwtHeader(credentials); var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); return(handler.WriteToken(secToken)); }
/// <summary> /// Generates a JWT. /// NOTE: THIS METHOD DOES NOT AUTHENTICATE USER CREDENTIALS. /// Any user authentication must be done prior to calling this method. /// /// The expiration time is expressed as a unix/posix integer in UTC. /// </summary> /// <param name="userId">The user's ID</param> /// <param name="tzOffset">The user's timezone offset from UTC in minutes</param> /// <param name="expMinutes"> /// An optional specification of how long the token is valid (in seconds). /// Must be positive to be considered. /// </param> /// <param name="assesmentId">Optionally brands the new token with an assessment ID in the payload</param> /// <returns></returns> public static string GenerateToken(int userId, string tzOffset, int expSeconds, int?assessmentId, string scope) { // Build securityKey. For uniqueness, append the user identity (userId) var securityKey = new Microsoft .IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetSecret() + userId)); // Build credentials var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials (securityKey, SecurityAlgorithms.HmacSha256Signature); // Finally create a Token var header = new JwtHeader(credentials); // Determine the expiration (server time) of the token int jwtExpiryMinutes = 60; string expMinutesConfig = ConfigurationManager.AppSettings["JWT Expiry Minutes"]; if (expMinutesConfig != null) { int.TryParse(expMinutesConfig, out jwtExpiryMinutes); } int secondsUntilExpiry = (jwtExpiryMinutes * 60); // If a non-zero expSeconds was provided, override the expiration if (expSeconds > 0) { secondsUntilExpiry = expSeconds; } var payload = new JwtPayload { { "aud", "CSET_AUD" }, { "iss", "CSET_ISS" }, { "exp", Utilities.UnixTime() + secondsUntilExpiry }, { Constants.Token_UserId, userId }, { Constants.Token_TimezoneOffsetKey, tzOffset }, { "scope", scope } }; // Include the current AssessmentId if one was provided if (assessmentId != null) { payload.Add(Constants.Token_AssessmentId, assessmentId); } // Build the token var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); return(handler.WriteToken(secToken)); }
/// <summary> /// Creates the JWT header /// </summary> /// <param name="token">The token.</param> /// <param name="keyVaultCredentials">The credentials.</param> /// <returns>The JWT header</returns> protected virtual JwtHeader CreateHeader(Token token, AzureKeyVaultSigningCredentials keyVaultCredentials) { var header = new JwtHeader(keyVaultCredentials); if (keyVaultCredentials != null) { header.Add("kid", _options.KeyIdentifier); } return(header); }
private static JwtSecurityToken GeneroiJwtToken(JwtPayload payload) { SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(salausAvain)); SigningCredentials credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); JwtHeader header = new JwtHeader(credentials); JwtSecurityToken secToken = new JwtSecurityToken(header, payload); return(secToken); }
public void WrapKey_Failure() { var keyEncryptionKey = SymmetricJwk.GenerateKey(128); var wrapper = new AesKeyWrapper(keyEncryptionKey.K, EncryptionAlgorithm.A256CbcHS512, KeyManagementAlgorithm.A128KW); var destination = new byte[0]; var header = new JwtHeader(); Assert.Throws <ArgumentException>(() => wrapper.WrapKey(null, header, destination)); Assert.Equal(0, header.Count); }
/// <inheritsdoc /> public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination) { if (header is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.header); } var contentEncryptionKey = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey); int bufferSize = _saltSizeInBytes + _algorithmNameLength + 1; byte[]? bufferToReturn = null; Span <byte> buffer = bufferSize > Pbkdf2.SaltSizeThreshold + 18 + 1 // 18 = max alg name length ? (bufferToReturn = ArrayPool <byte> .Shared.Rent(bufferSize)) : stackalloc byte[Pbkdf2.SaltSizeThreshold + 18 + 1]; buffer = buffer.Slice(0, bufferSize); _saltGenerator.Generate(buffer.Slice(_algorithmNameLength + 1)); buffer[_algorithmNameLength] = 0x00; _algorithm.EncodedUtf8Bytes.CopyTo(buffer); Span <byte> derivedKey = stackalloc byte[KeySizeThreshold].Slice(0, _keySizeInBytes); Pbkdf2.DeriveKey(_password, buffer, _hashAlgorithm, _iterationCount, derivedKey); Span <byte> salt = buffer.Slice(_algorithmNameLength + 1, _saltSizeInBytes); int saltLengthB64 = Base64Url.GetArraySizeRequiredToEncode(salt.Length); byte[]? arrayToReturn = null; Span <byte> b64Salt = saltLengthB64 > Pbkdf2.SaltSizeThreshold * 4 / 3 ? (arrayToReturn = ArrayPool <byte> .Shared.Rent(saltLengthB64)) : stackalloc byte[Pbkdf2.SaltSizeThreshold * 4 / 3]; try { int length = Base64Url.Encode(salt, b64Salt); header.Add(JwtHeaderParameterNames.P2s, Utf8.GetString(b64Salt.Slice(0, saltLengthB64))); header.Add(JwtHeaderParameterNames.P2c, _iterationCount); using var keyWrapper = new AesKeyWrapper(derivedKey, EncryptionAlgorithm, _keyManagementAlgorithm); return(keyWrapper.WrapKey(contentEncryptionKey, header, destination)); } finally { if (bufferToReturn != null) { ArrayPool <byte> .Shared.Return(bufferToReturn); } if (arrayToReturn != null) { ArrayPool <byte> .Shared.Return(arrayToReturn); } } }
private TokenSystem() { authOptions = new AuthOptions(); // Finally create a Token header = new JwtHeader(authOptions.credentials); handler = new JwtSecurityTokenHandler(); // And finally when you received token from client // you can either validate it or try to read }
public void JwtHeader_Defaults() { JwtHeader jwtHeader = new JwtHeader(); Assert.IsFalse(jwtHeader.ContainsValue(JwtConstants.HeaderType), "jwtHeader.ContainsValue( JwtConstants.HeaderType )"); Assert.IsFalse(jwtHeader.ContainsValue(JwtHeaderParameterNames.Typ), "jwtHeader.ContainsValue( JwtConstans.ReservedHeaderParameters.Type )"); Assert.IsFalse(jwtHeader.ContainsKey(JwtHeaderParameterNames.Alg), "!jwtHeader.ContainsKey( JwtHeaderParameterNames.Algorithm )"); Assert.IsNull(jwtHeader.Alg, "jwtHeader.SignatureAlgorithm == null"); Assert.IsNull(jwtHeader.SigningCredentials, "jwtHeader.SigningCredentials != null"); Assert.IsNotNull(jwtHeader.SigningKeyIdentifier, "jwtHeader.SigningKeyIdentifier == null"); Assert.AreEqual(jwtHeader.SigningKeyIdentifier.Count, 0, "jwtHeader.SigningKeyIdentifier.Count !== 0"); Assert.AreEqual(jwtHeader.Comparer.GetType(), StringComparer.Ordinal.GetType(), "jwtHeader.Comparer.GetType() != StringComparer.Ordinal.GetType()"); }
/// <summary> /// Creates the JWT header /// </summary> /// <param name="token">The token.</param> /// <param name="credential">The credentials.</param> /// <returns>The JWT header</returns> protected virtual async Task<JwtHeader> CreateHeaderAsync(Token token, SecurityKey key) { JwtHeader header = null; #if DOTNET5_4 header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)); #elif NET451 header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest)); var x509key = key as X509SecurityKey; if (x509key != null) { header.Add("kid", await _keyService.GetKidAsync(x509key.Certificate)); header.Add("x5t", await _keyService.GetKidAsync(x509key.Certificate)); } #endif return header; }
public static JwtSecurityToken Create(string issuer, string originalIssuer, SigningCredentials signingCredentials) { JwtPayload payload = new JwtPayload(issuer, "urn:uri", ClaimSets.Simple(issuer, originalIssuer), DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(10)); JwtHeader header = new JwtHeader(signingCredentials); return new JwtSecurityToken(header, payload, header.Encode() + "." + payload.Encode() + "."); }
public static JwtSecurityToken CreateJwtSecurityToken(string issuer, string originalIssuer, IEnumerable<Claim> claims, SigningCredentials signingCredentials) { JwtPayload payload = new JwtPayload(issuer, "urn:uri", claims, DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(10)); JwtHeader header = new JwtHeader(signingCredentials); return new JwtSecurityToken(header, payload); }
/*private string GetSignedJwtToken(string rsaKeyFilePath, X509Certificate2 cert, string url) { //var claimsetSerialized = @"{""token_class"":""solution_assertion"",""token_type"":""Bearer""" + // @",""jti"":""" + new Random().Next().ToString() + @"""" + // @",""iss"":""" + cert.Subject + @""",""sub"":""" + cert.Subject + @"""" + // @",""aud"":""" + url + @""",""iat"":""" + DateTimeHelper.WindowsToUnix(DateTime.Now).ToString() + @"""" + // @",""exp"":""" + DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString() + @"""}"; // header //var headerSerialized = @"{""typ"":""JWT"", ""alg"":""RS256""}"; var header = new JwtHeaderDto { Typ = "JWT", Alg = "RS256" }; // encoded header var headerSerialized = JsonConvert.Serialize(header); var headerBytes = Encoding.UTF8.GetBytes(headerSerialized); var headerEncoded = Convert.ToBase64String(headerBytes); // encoded claimset var claimset = new JwtClaimDto { TokenClass = "solution_assertion", TokenType = "Bearer", Jti = new Random().Next().ToString(), Iss = cert.Subject, Sub = cert.Subject, Aud = url, Iat = DateTimeHelper.WindowsToUnix(DateTime.Now).ToString(), Exp = DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString() }; //var claimset = new JwtPayload //{ // Jti = new Random().Next().ToString(), // Iss = cert.Subject, // Sub = cert.Subject, // Aud = url, // Iat = DateTimeHelper.WindowsToUnix(DateTime.Now).ToString(), // Exp = DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString(), // Claims = new List<Claim>() { new Claim("token_class", "solution_assertion"), new Claim("token_type", "Bearer") } //}; //var claimset = new JwtPayload(); //var claims = new List<Claim>(); //claims.Add(new Claim("token_class", "solution_assertion")); //claims.Add(new Claim("token_type", "Bearer")); //claims.Add(new Claim("jti", new Random().Next().ToString())); //claims.Add(new Claim("iss", cert.Subject)); //claims.Add(new Claim("sub", cert.Subject)); //claims.Add(new Claim("aud", url)); //claims.Add(new Claim("iat", DateTimeHelper.WindowsToUnix(DateTime.Now).ToString())); //claims.Add(new Claim("exp", DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString())); //claimset.AddClaims(claims); var claimsetSerialized = JsonConvert.Serialize(claimset); var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized); var claimsetEncoded = Convert.ToBase64String(claimsetBytes); // input var input = String.Join(".", headerEncoded, claimsetEncoded); var inputBytes = Encoding.UTF8.GetBytes(input); //var signatureBytes = rsaKey.SignData(inputBytes, "SHA256"); var signature = ShaWithRsaSigner.Sign(input, rsaKeyFilePath, "SHA256"); var signatureBytes = Encoding.UTF8.GetBytes(signature); var signatureEncoded = Convert.ToBase64String(signatureBytes); // jwt return String.Join(".", input, signatureEncoded); }*/ private string GetSignedJwtToken(RSACryptoServiceProvider rsa, X509Certificate2 cert, string url) { var claims = new List<Claim>(); claims.Add(new Claim("token_class", "solution_assertion")); claims.Add(new Claim("token_type", "Bearer")); claims.Add(new Claim("jti", new Random().Next().ToString())); claims.Add(new Claim("sub", cert.Subject)); var payload = new JwtPayload(cert.Issuer, url, claims, DateTime.Now, DateTime.Now.AddMinutes(5)); //var cert = new X509Certificate2(Encoding.UTF8.GetBytes(certificate.Encoded)); //var signingCredentials = new X509SigningCredentials(cert); //var payload = new JwtPayload(cert.Subject,url, DateTime.Now,DateTime.Now.AddMinutes(5)); //var claims = new List<Claim>(); //claims.Add(new Claim("token_class", "solution_assertion")); //claims.Add(new Claim("token_type", "Bearer")); //claims.Add(new Claim("jti", new Random().Next().ToString())); //claims.Add(new Claim("iss", cert.Subject)); //claims.Add(new Claim("sub", cert.Subject)); //claims.Add(new Claim("aud", url)); //claims.Add(new Claim("iat", DateTimeHelper.WindowsToUnix(DateTime.Now).ToString())); //claims.Add(new Claim("exp", DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString())); //payload.Exp = DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)); //payload.Iat = DateTimeHelper.WindowsToUnix(DateTime.Now); //payload.AddClaims(claims); //var keyBytes = GetBytes(privateKey.Encoded); //var key = new InMemorySymmetricSecurityKey(keyBytes); var key = new RsaSecurityKey(rsa); var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); var header = new JwtHeader(signingCredentials); var token = new JwtSecurityToken(header, payload); var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); try { var jsonToken = jwtSecurityTokenHandler.WriteToken(token); return jsonToken; } catch (Exception) { // todo: Log exception } return null; }
/// <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); }
/// <summary> /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class where the <see cref="JwtHeader"/> contains the crypto algorithms applied to the encoded <see cref="JwtHeader"/> and <see cref="JwtPayload"/>. The jwtEncodedString is the result of those operations. /// </summary> /// <param name="header">Contains JSON objects representing the cryptographic operations applied to the JWT and optionally any additional properties of the JWT</param> /// <param name="payload">Contains JSON objects representing the claims contained in the JWT. Each claim is a JSON object of the form { Name, Value }</param> /// <exception cref="ArgumentNullException">'header' is null.</exception> /// <exception cref="ArgumentNullException">'payload' is null.</exception> public JwtSecurityToken(JwtHeader header, JwtPayload payload) { if (header == null) { throw new ArgumentNullException("header"); } if (payload == null) { throw new ArgumentNullException("payload"); } this.header = header; this.payload = payload; }
/// <summary> /// Initializes a new instance of the <see cref="JwtSecurityToken"/> class where the <see cref="JwtHeader"/> contains the crypto algorithms applied to the encoded <see cref="JwtHeader"/> and <see cref="JwtPayload"/>. The jwtEncodedString is the result of those operations. /// </summary> /// <param name="header">Contains JSON objects representing the cryptographic operations applied to the JWT and optionally any additional properties of the JWT</param> /// <param name="payload">Contains JSON objects representing the claims contained in the JWT. Each claim is a JSON object of the form { Name, Value }</param> /// <param name="jwtEncodedString">The results of encoding and applying the cryptographic operations to the <see cref="JwtHeader"/> and <see cref="JwtPayload"/>.</param> /// <exception cref="ArgumentNullException">'header' is null.</exception> /// <exception cref="ArgumentNullException">'payload' is null.</exception> /// <exception cref="ArgumentNullException">'jwtEncodedString' is null.</exception> /// <exception cref="ArgumentException">'jwtEncodedString' contains only whitespace.</exception> /// <exception cref="ArgumentException">'jwtEncodedString' is not in JWS Compact serialized format.</exception> public JwtSecurityToken(JwtHeader header, JwtPayload payload, string jwtEncodedString) { if (header == null) { throw new ArgumentNullException("header"); } if (payload == null) { throw new ArgumentNullException("payload"); } if (jwtEncodedString == null) { throw new ArgumentNullException("jwtEncodedString"); } if (string.IsNullOrWhiteSpace(jwtEncodedString)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "jwtEncodedString")); } if (!Regex.IsMatch(jwtEncodedString, JwtConstants.JsonCompactSerializationRegex)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10709, "jwtEncodedString", jwtEncodedString)); } string[] tokenParts = jwtEncodedString.Split('.'); if (tokenParts.Length != 3) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10709, "jwtEncodedString", jwtEncodedString)); } this.header = header; this.payload = payload; this.rawData = jwtEncodedString; this.signature = tokenParts[2]; }
protected virtual Task<JwtHeader> CreateHeaderAsync(Token token) { JwtHeader header = new JwtHeader(new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Clients.FranceConnectSecret)), "HS256")); return Task.FromResult(header); }
/// <summary> /// Uses the <see cref="JwtSecurityToken(JwtHeader, JwtPayload, string, string, string)"/> constructor, first creating the <see cref="JwtHeader"/> and <see cref="JwtPayload"/>. /// <para>If <see cref="SigningCredentials"/> is not null, <see cref="JwtSecurityToken.RawData"/> will be signed.</para> /// </summary> /// <param name="issuer">the issuer of the token.</param> /// <param name="audience">the audience for this token.</param> /// <param name="subject">the source of the <see cref="Claim"/>(s) for this token.</param> /// <param name="notBefore">the notbefore time for this token.</param> /// <param name="expires">the expiration time for this token.</param> /// <param name="signingCredentials">contains cryptographic material for generating a signature.</param> /// <param name="signatureProvider">optional <see cref="SignatureProvider"/>.</param> /// <remarks>If <see cref="ClaimsIdentity.Actor"/> is not null, then a claim { actort, 'value' } will be added to the payload. <see cref="CreateActorValue"/> for details on how the value is created. /// <para>See <seealso cref="JwtHeader"/> for details on how the HeaderParameters are added to the header.</para> /// <para>See <seealso cref="JwtPayload"/> for details on how the values are added to the payload.</para></remarks> /// <para>If signautureProvider is not null, then it will be used to create the signature and <see cref="System.IdentityModel.Tokens.SignatureProviderFactory.CreateForSigning( SecurityKey, string )"/> will not be called.</para> /// <returns>A <see cref="JwtSecurityToken"/>.</returns> /// <exception cref="ArgumentException">if 'expires' <= 'notBefore'.</exception> public virtual JwtSecurityToken CreateToken(string issuer = null, string audience = null, ClaimsIdentity subject = null, DateTime? notBefore = null, DateTime? expires = null, SigningCredentials signingCredentials = null, SignatureProvider signatureProvider = null) { if (expires.HasValue && notBefore.HasValue) { if (notBefore >= expires) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10401, expires.Value, notBefore.Value)); } } // if not set, use defaults if (!expires.HasValue && !notBefore.HasValue) { DateTime now = DateTime.UtcNow; expires = now + TimeSpan.FromMinutes(TokenLifetimeInMinutes); notBefore = now; } JwtPayload payload = new JwtPayload(issuer, audience, subject == null ? null : subject.Claims, notBefore, expires); JwtHeader header = new JwtHeader(signingCredentials); if (subject != null && subject.Actor != null) { payload.AddClaim(new Claim(JwtRegisteredClaimNames.Actort, this.CreateActorValue(subject.Actor))); } string rawHeader = header.Base64UrlEncode(); string rawPayload = payload.Base64UrlEncode(); string rawSignature = string.Empty; string signingInput = string.Concat(rawHeader, ".", rawPayload); if (signatureProvider != null) { rawSignature = Base64UrlEncoder.Encode(this.CreateSignature(signingInput, null, null, signatureProvider)); } else if (signingCredentials != null) { rawSignature = Base64UrlEncoder.Encode(this.CreateSignature(signingInput, signingCredentials.SigningKey, signingCredentials.SignatureAlgorithm, signatureProvider)); } return new JwtSecurityToken(header, payload, rawHeader, rawPayload, rawSignature); }
public void JwtHeader_SigningKeyIdentifier() { var cert = KeyingMaterial.DefaultAsymmetricCert_2048; var header = new JwtHeader(new X509SigningCredentials(cert)); var payload = new JwtPayload( new Claim[]{new Claim("iss", "issuer")}); var jwt = new JwtSecurityToken(header, payload, header.Base64UrlEncode(), payload.Base64UrlEncode(), ""); var handler = new JwtSecurityTokenHandler(); var signedJwt = handler.WriteToken(jwt); SecurityToken token = null; var validationParameters = new TokenValidationParameters { IssuerSigningToken = new X509SecurityToken(cert), ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, }; handler.ValidateToken(signedJwt, validationParameters, out token); validationParameters = new TokenValidationParameters { IssuerSigningKey = new X509SecurityKey(cert), ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, }; handler.ValidateToken(signedJwt, validationParameters, out token); }
private string ConstructJWTAssertion(string sub, string boxSubType) { byte[] randomNumber = new byte[64]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(randomNumber); } var claims = new List<Claim>{ new Claim("sub", sub), new Claim("box_sub_type", boxSubType), new Claim("jti", Convert.ToBase64String(randomNumber)), }; var payload = new JwtPayload(this.boxConfig.ClientId, AUTH_URL, claims, null, DateTime.UtcNow.AddSeconds(30)); var header = new JwtHeader(signingCredentials: this.credentials); if (this.boxConfig.JWTPublicKeyId != null) header.Add("kid", this.boxConfig.JWTPublicKeyId); var token = new JwtSecurityToken(header, payload); var tokenHandler = new JwtSecurityTokenHandler(); string assertion = tokenHandler.WriteToken(token); return assertion; }
//public static byte[] GenerateRandomBytes(int length) //{ // // Create a buffer // byte[] randBytes; // if (length >= 1) // { // randBytes = new byte[length]; // } // else // { // randBytes = new byte[1]; // } // // Create a new RNGCryptoServiceProvider. // System.Security.Cryptography.RNGCryptoServiceProvider rand = // new System.Security.Cryptography.RNGCryptoServiceProvider(); // // Fill the buffer with random bytes. // rand.GetBytes(randBytes); // // return the bytes. // return randBytes; //} public static string JWTDecrypt(User user) { Log.Debug("Username:"******"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var jwtHeader = new JwtHeader(signingCred); JwtSecurityToken jwtToken = new JwtSecurityToken ( //issuer: "http://issuer.com", audience: "http://localhost" //, claims: new List<Claim>() { new Claim("username", user.Username) } //, lifetime: new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(expire)) //, signingCredentials: signingCred ); string tokenString = tokenhandler.WriteToken(jwtToken); return tokenString; }
/// <summary> /// Creates the JWT header /// </summary> /// <param name="token">The token.</param> /// <param name="keyVaultCredentials">The credentials.</param> /// <returns>The JWT header</returns> protected virtual JwtHeader CreateHeader(Token token, AzureKeyVaultSigningCredentials keyVaultCredentials) { var header = new JwtHeader(keyVaultCredentials); if (keyVaultCredentials != null) { header.Add("kid", _options.KeyIdentifier); } return header; }
/// <summary> /// Creates the JWT header /// </summary> /// <param name="credential">The credentials.</param> /// <returns>The JWT header</returns> private async Task<JwtHeader> CreateHeaderAsync(SigningCredentials credential) { var header = new JwtHeader(credential); var x509credential = credential as X509SigningCredentials; if (x509credential != null) { header.Add("kid", await _keyService.GetKidAsync(x509credential.Certificate)); } return header; }
public void CreateAndValidateTokens_MultipleAudiences() { List<string> errors = new List<string>(); var handler = new JwtSecurityTokenHandler(); var payload = new JwtPayload(); var header = new JwtHeader(); payload.AddClaims(ClaimSets.MultipleAudiences(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer)); var jwtToken = new JwtSecurityToken(header, payload); var jwt = handler.WriteToken(jwtToken); var validationParameters = new TokenValidationParameters { RequireExpirationTime = false, RequireSignedTokens = false, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, }; SecurityToken validatedJwt = null; var cp = handler.ValidateToken(jwt, validationParameters, out validatedJwt); var ci = new ClaimsIdentity(ClaimSets.MultipleAudiences(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer), AuthenticationTypes.Federation); var cpExpected = new ClaimsPrincipal(ci); var compareContext = new CompareContext(); if (!IdentityComparer.AreEqual<ClaimsPrincipal>(cp, cpExpected, compareContext)) { errors.Add("IdentityComparer.AreEqual<ClaimsPrincipal>(cp, cpExpected, compareContext)"); } var audiences = (validatedJwt as JwtSecurityToken).Audiences; var jwtAudiences = jwtToken.Audiences; if (!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, jwtAudiences)) { errors.Add("!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, jwtAudiences)"); } if (!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, IdentityUtilities.DefaultAudiences)) { errors.Add("!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, IdentityUtilities.DefaultAudiences)"); } TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors); }
public static IEnumerable<Claim> ClaimsPlus( IEnumerable<Claim> claims = null, SigningCredentials signingCredential = null, Lifetime lifetime = null, string issuer = null, string originalIssuer = null, string audience = null ) { string thisIssuer = issuer ?? ClaimsIdentity.DefaultIssuer; string thisOriginalIssuer = originalIssuer ?? thisIssuer; if ( claims != null ) { foreach ( Claim claim in claims ) yield return claim; } if ( signingCredential != null ) { JwtHeader header = new JwtHeader( signingCredential ); foreach ( string key in header.Keys ) { string value = header[key]; yield return new Claim( key, value, ClaimValueTypes.String, thisIssuer, thisOriginalIssuer ); } } if ( lifetime != null ) { yield return new Claim( JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(lifetime.Created.Value ).ToString(), ClaimValueTypes.String, thisIssuer, thisOriginalIssuer ); yield return new Claim( JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate( lifetime.Expires.Value ).ToString(), ClaimValueTypes.String, thisIssuer, thisOriginalIssuer ); } if ( audience != null ) { yield return new Claim( JwtRegisteredClaimNames.Aud, audience, ClaimValueTypes.String, thisIssuer, thisOriginalIssuer ); } if ( issuer != null ) { yield return new Claim( JwtRegisteredClaimNames.Iss, issuer, ClaimValueTypes.String, thisIssuer, thisOriginalIssuer ); } }
public DerivedJwtSecurityToken(JwtHeader header, JwtPayload payload, string encodedJwt) : base(header, payload, encodedJwt) { Init(); }
/// <summary> /// Creates the JWT header /// </summary> /// <param name="token">The token.</param> /// <param name="keyVaultCredentials">The credentials.</param> /// <returns>The JWT header</returns> protected virtual Task<JwtHeader> CreateHeaderAsync(Token token, AzureKeyVaultSigningCredentials keyVaultCredentials) { var header = new JwtHeader(keyVaultCredentials); if (keyVaultCredentials != null) { header.Add("kid", _options.KeyIdentifier); header.Add("x5t", _options.KeyIdentifier); } return Task.FromResult(header); }
private static string GetEncodedJwtHeader() { var jwtHeader = new JwtHeader { alg = "RS256", typ = "JWT" }; var header = JsonConvert.SerializeObject(jwtHeader); Debug.WriteLine("JWT Header: " + header); return Base64UrlEncode(header); }
public void NamedKeySecurityKeyIdentifierClause_Extensibility() { string clauseName = "kid"; string keyId = Issuers.GotJwt; NamedKeySecurityKeyIdentifierClause clause = new NamedKeySecurityKeyIdentifierClause(clauseName, keyId); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(clause); SigningCredentials signingCredentials = new SigningCredentials(KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest, keyIdentifier); JwtHeader jwtHeader = new JwtHeader(signingCredentials); SecurityKeyIdentifier ski = jwtHeader.SigningKeyIdentifier; Assert.AreEqual(ski.Count, 1, "ski.Count != 1 "); NamedKeySecurityKeyIdentifierClause clauseOut = ski.Find<NamedKeySecurityKeyIdentifierClause>(); Assert.IsNotNull(clauseOut, "NamedKeySecurityKeyIdentifierClause not found"); Assert.AreEqual(clauseOut.Name, clauseName, "clauseOut.Id != clauseId"); Assert.AreEqual(clauseOut.Id, keyId, "clauseOut.KeyIdentifier != keyId"); NamedKeySecurityToken NamedKeySecurityToken = new NamedKeySecurityToken(clauseName, keyId, new SecurityKey[] { KeyingMaterial.DefaultSymmetricSecurityKey_256 }); Assert.IsTrue(NamedKeySecurityToken.MatchesKeyIdentifierClause(clause), "NamedKeySecurityToken.MatchesKeyIdentifierClause( clause ), failed"); List<SecurityKey> list = new List<SecurityKey>() { KeyingMaterial.DefaultSymmetricSecurityKey_256 }; Dictionary<string, IList<SecurityKey>> keys = new Dictionary<string, IList<SecurityKey>>() { { "kid", list }, }; NamedKeyIssuerTokenResolver nkitr = new NamedKeyIssuerTokenResolver(keys: keys); SecurityKey sk = nkitr.ResolveSecurityKey(clause); Assert.IsNotNull(sk, "NamedKeySecurityToken.MatchesKeyIdentifierClause( clause ), failed"); }
/// <summary> /// Creates the JWT header /// </summary> /// <param name="token">The token.</param> /// <param name="credential">The credentials.</param> /// <returns>The JWT header</returns> protected virtual JwtHeader CreateHeader(Token token, SigningCredentials credential) { var header = new JwtHeader(credential); var x509credential = credential as X509SigningCredentials; if (x509credential != null) { header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash())); } return header; }
/// <summary> /// Decodes the string into the header, payload and signature /// </summary> /// <param name="jwtEncodedString">Base64Url encoded string.</param> internal void Decode(string jwtEncodedString) { string[] tokenParts = jwtEncodedString.Split('.'); if (tokenParts.Length != 3) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10709, "jwtEncodedString", jwtEncodedString)); } try { this.header = Base64UrlEncoder.Decode(tokenParts[0]).DeserializeJwtHeader(); // if present, "typ" should be set to "JWT" or "http://openid.net/specs/jwt/1.0" string type = null; if (this.header.TryGetValue(JwtHeaderParameterNames.Typ, out type)) { if (!(StringComparer.Ordinal.Equals(type, JwtConstants.HeaderType) || StringComparer.Ordinal.Equals(type, JwtConstants.HeaderTypeAlt))) { throw new SecurityTokenException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10702, JwtConstants.HeaderType, JwtConstants.HeaderTypeAlt, type)); } } } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "header", tokenParts[0], jwtEncodedString), ex); } try { this.payload = Base64UrlEncoder.Decode(tokenParts[1]).DeserializeJwtPayload(); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "payload", tokenParts[1], jwtEncodedString), ex); } this.rawData = jwtEncodedString; this.signature = tokenParts[2]; }