private static void SetToJwtHeader(IJwtHeader source, SystemJWT.JwtHeader target) { var headerJObj = JObject.FromObject(source); foreach (var key in headerJObj.Properties().Select(x => x.Name)) { target[key] = headerJObj[key]; } }
/// <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, overwriting any 'iss' claim in 'claims' if present.</param> /// <param name="audience">If this value is not null, a { aud, 'audience' } claim will be added, appending to any 'aud' claims in 'claims' if present.</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, overwriting any 'exp' claim in 'claims' if present.</param> /// <param name="notBefore">If notbefore.HasValue a { nbf, 'value' } claim is added, overwriting any 'nbf' claim in 'claims' if present.</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 LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX12401, LogHelper.MarkAsNonPII(expires.Value), LogHelper.MarkAsNonPII(notBefore.Value)))); } } Payload = new JwtPayload(issuer, audience, claims, notBefore, expires); Header = new JwtHeader(signingCredentials); RawSignature = string.Empty; }
/// <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 LogHelper.LogArgumentNullException("header"); } if (payload == null) { throw LogHelper.LogArgumentNullException("payload"); } Header = header; Payload = payload; RawSignature = string.Empty; }
/// <summary> /// Initializes an instance of <see cref="JwtSecurityToken"/> where the <see cref="JwtHeader"/> contains the crypto algorithms applied to the innerToken <see cref="JwtSecurityToken"/>. /// </summary> /// <param name="header">Defines cryptographic operations applied to the 'innerToken'.</param> /// <param name="innerToken"></param> /// <param name="rawEncryptedKey">base64urlencoded key</param> /// <param name="rawHeader">base64urlencoded JwtHeader</param> /// <param name="rawInitializationVector">base64urlencoded initialization vector.</param> /// <param name="rawCiphertext">base64urlencoded encrypted innerToken</param> /// <param name="rawAuthenticationTag">base64urlencoded authentication tag.</param> /// <exception cref="ArgumentNullException">'header' is null.</exception> /// <exception cref="ArgumentNullException">'innerToken' is null.</exception> /// <exception cref="ArgumentNullException">'rawHeader' is null.</exception> /// <exception cref="ArgumentNullException">'rawEncryptedKey' is null.</exception> /// <exception cref="ArgumentNullException">'rawInitialVector' is null or whitespace.</exception> /// <exception cref="ArgumentNullException">'rawCiphertext' is null or whitespace.</exception> /// <exception cref="ArgumentNullException">'rawAuthenticationTag' is null or whitespace.</exception> public JwtSecurityToken(JwtHeader header, JwtSecurityToken innerToken, string rawHeader, string rawEncryptedKey, string rawInitializationVector, string rawCiphertext, string rawAuthenticationTag) { if (header == null) { throw LogHelper.LogArgumentNullException(nameof(header)); } if (innerToken == null) { throw LogHelper.LogArgumentNullException(nameof(innerToken)); } if (rawEncryptedKey == null) { throw LogHelper.LogArgumentNullException(nameof(rawEncryptedKey)); } if (string.IsNullOrEmpty(rawInitializationVector)) { throw LogHelper.LogArgumentNullException(nameof(rawInitializationVector)); } if (string.IsNullOrEmpty(rawCiphertext)) { throw LogHelper.LogArgumentNullException(nameof(rawCiphertext)); } if (string.IsNullOrEmpty(rawAuthenticationTag)) { throw LogHelper.LogArgumentNullException(nameof(rawAuthenticationTag)); } Header = header; InnerToken = innerToken; RawData = string.Join(".", rawHeader, rawEncryptedKey, rawInitializationVector, rawCiphertext, rawAuthenticationTag); RawHeader = rawHeader; RawEncryptedKey = rawEncryptedKey; RawInitializationVector = rawInitializationVector; RawCiphertext = rawCiphertext; RawAuthenticationTag = rawAuthenticationTag; }
/// <summary> /// Decodes the string into the header, payload and signature. /// </summary> /// <param name="tokenParts">the tokenized string.</param> /// <param name="rawData">the original token.</param> internal void Decode(string[] tokenParts, string rawData) { IdentityModelEventSource.Logger.WriteInformation(LogMessages.IDX10716, rawData); try { Header = JwtHeader.Base64UrlDeserialize(tokenParts[0]); } catch (Exception ex) { throw LogHelper.LogExceptionMessage(new ArgumentException(String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10729, tokenParts[0], rawData), ex)); } if (tokenParts.Length == JwtConstants.JweSegmentCount) { DecodeJwe(tokenParts); } else { DecodeJws(tokenParts); } RawData = rawData; }
/// <summary> /// Decodes the string into the header, payload and signature. /// </summary> /// <param name="tokenParts">the tokenized string.</param> /// <param name="rawData">the original token.</param> internal void Decode(string[] tokenParts, string rawData) { LogHelper.LogInformation(LogMessages.IDX12716, rawData); try { Header = JwtHeader.Base64UrlDeserialize(tokenParts[0]); } catch (Exception ex) { throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX12729, tokenParts[0], rawData), ex)); } if (tokenParts.Length == JwtConstants.JweSegmentCount) { DecodeJwe(tokenParts); } else { DecodeJws(tokenParts); } RawData = rawData; }
private string GenerarToken(Usuario usuario, Guid idLogin, List <Rol> roles, DateTime vigencia) { var header = new System.IdentityModel.Tokens.Jwt.JwtHeader( new SigningCredentials( new SymmetricSecurityKey( Encoding.UTF8.GetBytes("7Yi90?r$ft%.op1=yui") ), SecurityAlgorithms.HmacSha256) ); var claims = new List <Claim>(); if (roles != null) { foreach (var rol in roles) { claims.Add(new Claim(ClaimTypes.Role, rol.Nombre)); } } claims.Add(new Claim(JwtRegisteredClaimNames.Jti, idLogin.ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.NameId, usuario.Id.ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.UniqueName, string.Concat(usuario.Nombre, " ", usuario.ApellidoPaterno, " ", usuario.ApellidoMaterno))); claims.Add(new Claim(JwtRegisteredClaimNames.Email, usuario.Correo)); var payload = new JwtPayload( issuer: "yunntech", audience: "yunntech", claims: claims, notBefore: DateTime.Now, expires: vigencia ); var token = new JwtSecurityToken(header, payload); return(new JwtSecurityTokenHandler().WriteToken(token)); }
private static string GenerateToken(string seckey, string apikey) { var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(seckey)); /* * // Create JWT credentials * var encryptingCredentials = new EncryptingCredentials(securityKey, * Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256 * ); */ var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256); // Create JWT header IDictionary <string, string> D = new Dictionary <string, string> { ["Typ"] = "JWT", ["Alg"] = "HS256", ["Kid"] = apikey }; var header = new System.IdentityModel.Tokens.Jwt.JwtHeader(credentials, D); ///////////////////////////////////////////////// var payload = new JwtPayload( claims: new[] { new Claim(JwtRegisteredClaimNames.Sub, "Filbert"), new Claim(JwtRegisteredClaimNames.Jti, System.Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Sid, System.Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iss, "tinkoff_mobile_bank_api"), new Claim(JwtRegisteredClaimNames.Nbf, DateTime.UtcNow.ToString()), new Claim(JwtRegisteredClaimNames.Aud, "tinkoff.cloud.stt"), new Claim(JwtRegisteredClaimNames.Exp, DateTime.UtcNow.AddDays(1).ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()) } ); var secToken = new JwtSecurityToken( header, payload); //signingCredentials: credentials, secToken.Header.Add("kid", "bnZ6cWRvcWJncWNud2dqcGxtZ21ndXVvZXdjaWpueHk=m.rogencovfilbert"); var handler = new JwtSecurityTokenHandler(); return(handler.WriteToken(secToken)); }