/// <summary> /// Generate a JWT with the provided information and sign it with the given secret. /// </summary> /// <param name="algorithm">The encryption type - default:HS256</param> /// <returns>Signed JWT authorizing the grants configured on this object</returns> public string ToJWT(JwtHashAlgorithm algorithm = JwtHashAlgorithm.HS256) { var headers = new Dictionary <string, object>(); headers.Add("cty", "twilio-fpa;v=1"); int now = ConvertToUnixTimestamp(DateTime.UtcNow); var grantPayload = new Dictionary <string, object>(); if (this.Identity != null) { grantPayload.Add("identity", this.Identity); } foreach (IGrant grant in this.Grants) { grantPayload.Add(grant.GetGrantKey(), grant.GetPayload()); } var payload = new Dictionary <string, object>(); payload.Add("jti", String.Format("{0}-{1}", _signingKeySid, now)); payload.Add("iss", _signingKeySid); payload.Add("sub", _accountSid); payload.Add("exp", now + Ttl); payload.Add("grants", grantPayload); if (this.Nbf != null) { payload.Add("nbf", this.Nbf); } return(JsonWebToken.Encode(headers, payload, _secret, algorithm)); }
/// <summary> /// Generate a JWT with the provided information and sign it with the given secret. /// </summary> /// <param name="algorithm">The encryption type - default:HS256</param> /// <returns>Signed JWT authorizing the grants configured on this object</returns> public string ToJwt(JwtHashAlgorithm algorithm = JwtHashAlgorithm.HS256) { var headers = new Dictionary <string, object> { { "cty", "twilio-fpa;v=1" } }; var now = ConvertToUnixTimestamp(DateTime.UtcNow); var grantPayload = new Dictionary <string, object>(); if (Identity != null) { grantPayload.Add("identity", Identity); } foreach (var grant in Grants) { grantPayload.Add(grant.GetGrantKey(), grant.GetPayload()); } var payload = new Dictionary <string, object> { { "jti", $"{_signingKeySid}-{now}" }, { "iss", _signingKeySid }, { "sub", _accountSid }, { "exp", now + Ttl }, { "grants", grantPayload } }; if (Nbf != null) { payload.Add("nbf", Nbf); } return(JsonWebToken.Encode(headers, payload, _secret, algorithm)); }
/// <summary> /// JWT /// </summary> /// <param name="payload">载体(有效信息)</param> /// <param name="keyBytes">盐</param> /// <param name="algorithm">加密算法</param> /// <returns></returns> public static string Encode(object payload, byte[] keyBytes, JwtHashAlgorithm algorithm) { var segments = new List <string>(); ///jWT head 默认有2部分构成 var header = new { alg = algorithm.ToString(), typ = "JWT" }; byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None)); byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None)); // JWT有三部分组成 分别是 head.payload.signature //1.将头部信息编码构成JWT的第一部分 segments.Add(headerBytes.Base64UrlEncode()); //2.将payload信息编码构成JWT的第二部分 segments.Add(payloadBytes.Base64UrlEncode()); //3.把base64后的头部信息跟base64后的paylod用.连接成字符串用于构成jwt的第三部分 var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); //4. 根据head中的加密方式再加上盐(key)进行加密获得 jwt的第三部分 signature byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign); segments.Add(signature.Base64UrlEncode()); //5.把这三部分用 . 拼接成字符串 就是最终的jwt信息了 return(string.Join(".", segments.ToArray())); }
public void RefreshToken_Basic(JwtHashAlgorithm alg, string secretBase64) { var container = TestContainerBuilder.GetContainer(builder => { builder.RegisterType <SymmetricKeyTokenGenerator>() .Keyed <ITokenGenerator>(JwtHashAlgorithm.HS256) .SingleInstance(); builder.RegisterType <AsymmetricKeyPairTokenGenerator>() .Keyed <ITokenGenerator>(JwtHashAlgorithm.RS256) .SingleInstance(); }); var tokenGenerator = container.ResolveKeyed <ITokenGenerator>(alg); var issueTime = DateTime.UtcNow; var userId = 165; var tid = 111; var secret = Convert.FromBase64String(secretBase64); var refreshToken = new JsonWebToken().Encode(new { typ = "refresh_token", sub = $"{userId}", tid = $"{tid}", exp = new DateTimeOffset(issueTime.AddHours(8)).ToUnixTimeSeconds(), iat = new DateTimeOffset(issueTime).ToUnixTimeSeconds(), iss = "issuer", aud = "*" }, secret, alg); var refreshToken2 = tokenGenerator.GenerateRefreshToken(tid, issueTime, userId); Assert.Equal(refreshToken, refreshToken2); }
private static string Encode(object payload, byte[] keyBytes, JwtHashAlgorithm algorithm) { var segments = new List <string>(); var header = new { alg = algorithm.ToString(), typ = "JWT" }; byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None)); byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None)); //计算A segments.Add(Base64UrlEncode(headerBytes)); //计算B segments.Add(Base64UrlEncode(payloadBytes)); var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); //利用A和B计算C byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign); segments.Add(Base64UrlEncode(signature)); return(string.Join(".", segments.ToArray())); }
public static string Encode(object payload, byte[] keyBytes, JwtHashAlgorithm algorithm) { var segments = new List <string>(); var header = new { alg = algorithm.ToString(), typ = "JWT" }; //byte[] headerBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(header)); //byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload)); //byte[] payloadBytes = Encoding.UTF8.GetBytes(@"{"iss":"*****@*****.**","scope":"https://www.googleapis.com/auth/prediction","aud":"https://accounts.google.com/o/oauth2/token","exp":1328554385,"iat":1328550785}"); byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None)); byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None)); //byte[] payloadBytes = Encoding.UTF8.GetBytes(@"{"iss":"*****@*****.**","scope":"https://www.googleapis.com/auth/prediction","aud":"https://accounts.google.com/o/oauth2/token","exp":1328554385,"iat":1328550785}"); segments.Add(Base64UrlEncode(headerBytes)); segments.Add(Base64UrlEncode(payloadBytes)); var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign); segments.Add(Base64UrlEncode(signature)); return(string.Join(".", segments.ToArray())); }
/// <summary> /// This constructor sets the secret and the audience for the handler. /// </summary> /// <param name="id">The identifier.</param> /// <param name="algo">The hash algorithm to be used.</param> /// <param name="base64Secret">The secret byte array as a base64 string.</param> /// <param name="audience">The audience. This is compared when the token is received and validated. /// By default it is set to 'comms'</param> public JwtTokenAuthenticationHandler(string id, JwtHashAlgorithm algo, string base64Secret, string audience = "comms") : base(id, nameof(JwtTokenAuthenticationHandler)) { mAlgorithm = algo; mSecret = Convert.FromBase64String(base64Secret); mAudience = audience; }
private static byte[] ComputeHash(JwtHashAlgorithm algorithm, byte[] key, byte[] value) { HashAlgorithm hashAlgorithm; switch (algorithm) { case JwtHashAlgorithm.HS256: hashAlgorithm = new HMACSHA256(key); break; case JwtHashAlgorithm.HS384: hashAlgorithm = new HMACSHA384(key); break; case JwtHashAlgorithm.HS512: hashAlgorithm = new HMACSHA512(key); break; default: throw new Exception($"Unsupported hash algorithm: '{algorithm}'."); } using (hashAlgorithm) { return(hashAlgorithm.ComputeHash(value)); } }
public static string Encode(T payload, byte[] keyBytes, JwtHashAlgorithm algorithm) { var segments = new List <string>(); using (var s = new MemoryStream()) using (var w = new StreamWriter(s)) { // add header var header = new JwtHeader { Algorithm = algorithm.ToString(), Type = "JWT" }; //var headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None)); _headerSerializer.Serialize(w, header); var headerBytes = s.ToArray(); segments.Add(Base64UrlEncode(headerBytes)); // add payload //var payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None)); //var payloadBytes = Encoding.UTF8.GetBytes(@"{"iss":"*****@*****.**","scope":"https://www.googleapis.com/auth/prediction","aud":"https://accounts.google.com/o/oauth2/token","exp":1328554385,"iat":1328550785}"); s.SetLength(0); _payloadSerializer.Serialize(w, payload); var payloadBytes = s.ToArray(); segments.Add(Base64UrlEncode(payloadBytes)); } // add signature var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); var signature = HashAlgorithms[algorithm](keyBytes, bytesToSign); segments.Add(Base64UrlEncode(signature)); return(string.Join(".", segments.ToArray())); }
/// <summary> /// This constructor sets the secret and the audience for the handler. /// </summary> /// <param name="id">The identifier.</param> /// <param name="algo">The hash algorithm to be used.</param> /// <param name="secret">The secret byte array.</param> /// <param name="audience">The audience. This is compared when the token is received and validated. /// By default it is set to 'comms'</param> public JwtTokenAuthenticationHandler(string id, JwtHashAlgorithm algo, byte[] secret, string audience = "comms") : base(id, nameof(JwtTokenAuthenticationHandler)) { mAlgorithm = algo; mSecret = secret; mAudience = audience; }
/// <summary> /// This method adds the Jwt authentication handler to the Microservice. /// </summary> /// <typeparam name="P">The pipeline type.</typeparam> /// <param name="pipeline">The pipeline.</param> /// <param name="identifier">The encryption type identifier. /// This is will be used when assigning the handler to a channel or collector.</param> /// <param name="algo">The HMAC algorithm.</param> /// <param name="secret">This is the byte array used for the HMAC secret.</param> /// <param name="audience">This is the audience value generated for the token and used for validation when a token is received.</param> /// <param name="action">The action on the handler.</param> /// <returns>The pipeline.</returns> public static P AddAuthenticationHandlerJwtToken <P>(this P pipeline , string identifier , JwtHashAlgorithm algo , byte[] secret , string audience = "comms" , Action <IAuthenticationHandler> action = null) where P : IPipeline { if (algo == JwtHashAlgorithm.None) { throw new ArgumentOutOfRangeException("JwtHashAlgorithm.None is not supported."); } if (secret == null || secret.Length == 0) { throw new ArgumentNullException($"secret cannot be null or empty for {nameof(AddJwtTokenAuthenticationHandler)}"); } var handler = new JwtTokenAuthenticationHandler(algo, secret, audience: audience); action?.Invoke(handler); pipeline.Service.Security.RegisterAuthenticationHandler(identifier, handler); return(pipeline); }
/// <summary> /// This method adds the Jwt authentication handler to the Microservice. /// </summary> /// <typeparam name="P">The pipeline type.</typeparam> /// <param name="pipeline">The pipeline.</param> /// <param name="identifier">The encryption type identifier. /// This is will be used when assigning the handler to a channel or collector.</param> /// <param name="algo">The HMAC algorithm.</param> /// <param name="base64Secret">This is the base64 encoded byte array used for the HMAC secret.</param> /// <param name="action">The action on the handler.</param> /// <returns>The pipeline.</returns> public static P AddJwtTokenAuthenticationHandler <P>(this P pipeline , string identifier , JwtHashAlgorithm algo , string base64Secret , Action <IAuthenticationHandler> action = null) where P : IPipeline { if (algo == JwtHashAlgorithm.None) { throw new ArgumentOutOfRangeException("JwtHashAlgorithm.None is not supported."); } if (string.IsNullOrEmpty(base64Secret)) { throw new ArgumentNullException($"base64Secret cannot be null or empty for {nameof(AddJwtTokenAuthenticationHandler)}"); } var handler = new JwtTokenAuthenticationHandler(algo, base64Secret); action?.Invoke(handler); pipeline.Service.Security.RegisterAuthenticationHandler(identifier, handler); return(pipeline); }
/// <summary> /// This method adds the Jwt authentication handler to the Microservice. /// </summary> /// <typeparam name="P">The pipeline type.</typeparam> /// <param name="pipeline">The pipeline.</param> /// <param name="identifier">The encryption type identifier. /// This is will be used when assigning the handler to a channel or collector.</param> /// <param name="algo">The HMAC algorithm.</param> /// <param name="secretSetter">This is the fucntion to return the base64 encoded secret from configuration.</param> /// <param name="action">The action on the handler.</param> /// <returns>The pipeline.</returns> public static P AddJwtTokenAuthenticationHandler <P>(this P pipeline , string identifier , JwtHashAlgorithm algo , Func <IEnvironmentConfiguration, string> secretSetter , Action <IAuthenticationHandler> action = null) where P : IPipeline { if (algo == JwtHashAlgorithm.None) { throw new ArgumentOutOfRangeException("JwtHashAlgorithm.None is not supported."); } if (secretSetter == null) { throw new ArgumentNullException($"secretSetter cannot be null or empty for {nameof(AddJwtTokenAuthenticationHandler)}"); } byte[] bySecret = null; try { bySecret = Convert.FromBase64String(secretSetter(pipeline.Configuration)); } catch (Exception ex) { throw new AuthenticationHandlerInvalidSecretException(ex); } var handler = new JwtTokenAuthenticationHandler(algo, bySecret); action?.Invoke(handler); pipeline.Service.Security.RegisterAuthenticationHandler(identifier, handler); return(pipeline); }
public static string Encode(object payload, string key, JwtHashAlgorithm algorithm) { var segments = new List <string>(); var header = new { typ = "JWT", alg = algorithm.ToString() }; JsonSerializerSettings jsonSettings = new JsonSerializerSettings(); jsonSettings.NullValueHandling = NullValueHandling.Ignore; jsonSettings.DefaultValueHandling = DefaultValueHandling.Ignore; byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None)); byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None, jsonSettings)); segments.Add(Base64UrlEncode(headerBytes)); segments.Add(Base64UrlEncode(payloadBytes)); var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); var keyBytes = Encoding.UTF8.GetBytes(key); byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign); segments.Add(Base64UrlEncode(signature)); return(string.Join(".", segments.ToArray())); }
/// <summary> /// Generate a JWT with the provided information and sign it with the given secret. /// </summary> /// <param name="algorithm">The encryption type - default:HS256</param> /// <returns>Signed JWT authorizing the grants configured on this object</returns> public string ToJWT(JwtHashAlgorithm algorithm=JwtHashAlgorithm.HS256) { var headers = new Dictionary<string, object>(); headers.Add("cty", "twilio-fpa;v=1"); int now = ConvertToUnixTimestamp(DateTime.UtcNow); var grantPayload = new Dictionary<string, object>(); if (this.Identity != null) { grantPayload.Add("identity", this.Identity); } foreach (IGrant grant in this.Grants) { Console.Write(grant.GetGrantKey()); grantPayload.Add(grant.GetGrantKey(), grant.GetPayload()); } var payload = new Dictionary<string, object>(); payload.Add("jti", String.Format("{0}-{1}", _signingKeySid, now)); payload.Add("iss", _signingKeySid); payload.Add("sub", _accountSid); payload.Add("exp", now + Ttl); payload.Add("grants", grantPayload); if (this.Nbf != null) { payload.Add("nbf", this.Nbf); } return JsonWebToken.Encode(headers, payload, _secret, algorithm); }
/// <inheritdoc /> public override IJwtAlgorithm Create(JwtHashAlgorithm algorithm) { switch (algorithm) { case JwtHashAlgorithm.RS256: return(new RS256Algorithm(_certFactory())); default: throw new NotSupportedException($"For algorithm {Enum.GetName(typeof(JwtHashAlgorithm), algorithm)} please use the appropriate factory by implementing {nameof(IAlgorithmFactory)}"); } }
/// <summary> /// This method signs the token and returns it using JWS Compact Serialization notation. /// </summary> /// <param name="key">The key.</param> /// <returns>Returns a compact serialization key.</returns> public string ToString(byte[] key) { JwtHashAlgorithm algo = Header.SupportedAlgorithm; string b64joseHeader = JwtHelper.SafeBase64UrlEncode(Encoding.UTF8.GetBytes(Header.ToString())); string b64jwtClaimsSet = JwtHelper.SafeBase64UrlEncode(Encoding.UTF8.GetBytes(Claims.ToString())); string signature = JwtRoot.CalculateAuthSignature(algo, key, b64joseHeader, b64jwtClaimsSet); return($"{b64joseHeader}.{b64jwtClaimsSet}.{signature}"); }
public JwtCodecService(byte[] key, JwtHashAlgorithm algorithm = JwtHashAlgorithm.HS256, Dictionary <string, object> extraHeaders = null) { if (key == null) { throw new ArgumentNullException(nameof(key)); } this.key = key; this.algorithm = algorithm; this.extraHeaders = extraHeaders ?? new Dictionary <string, object>(0); }
/// <summary> /// Encodes a token to JWT by using secret key + a given algorithm. /// </summary> /// <param name="algorithm">Algorithm used for encoding. Default value is HS512.</param> /// <returns></returns> public string ToTokenString(JwtHashAlgorithm algorithm = JwtHashAlgorithm.HS512) { ExpirationDate = DateTime.Now.AddMinutes((int)TokenExpiration); ExpirationTime = Math.Round((ExpirationDate - StarterDate).TotalSeconds); return(JsonWebToken.Encode(new Dictionary <string, object> { { "exp", ExpirationTime }, { "Role", Role }, { "Information", Information }, { "TokenExpiration", TokenExpiration } }, TokenUtilities.TokenSecretKey, algorithm)); }
private static HMAC GetHashFunction(JwtHashAlgorithm algorithm, byte[] key) { switch (algorithm) { case JwtHashAlgorithm.HS256: return(new HMACSHA256(key)); case JwtHashAlgorithm.HS384: return(new HMACSHA384(key)); case JwtHashAlgorithm.HS512: return(new HMACSHA512(key)); default: throw new CryptographicException(Properties.Resources.InvalidJwtAlgorithm); } }
/// <inheritdoc /> public override IJwtAlgorithm Create(JwtHashAlgorithm algorithm) { switch (algorithm) { case JwtHashAlgorithm.RS256: var certificate = _certFactory(); #if NETSTANDARD1_3 return(new RS256Algorithm((RSACryptoServiceProvider)certificate.GetRSAPublicKey(), certificate.GetRSAPrivateKey())); #else return(new RS256Algorithm((RSACryptoServiceProvider)certificate.PublicKey.Key, (RSA)certificate.PrivateKey)); #endif default: throw new NotSupportedException($"For algorithm {Enum.GetName(typeof(JwtHashAlgorithm), algorithm)} please use the appropriate factory by implementing {nameof(IAlgorithmFactory)}"); } }
private static byte[] ComputeHash(JwtHashAlgorithm algorithm, byte[] key, byte[] value) { var hashAlgorithm = algorithm switch { JwtHashAlgorithm.HS256 => (HashAlgorithm) new HMACSHA256(key), JwtHashAlgorithm.HS384 => new HMACSHA384(key), JwtHashAlgorithm.HS512 => new HMACSHA512(key), _ => throw new Exception($"Unsupported hash algorithm: '{algorithm}'."), }; using (hashAlgorithm) { return(hashAlgorithm.ComputeHash(value)); } }
/// <summary> /// Creates an AlgorithmFactory using the provided /// algorithm name. /// </summary> /// <param name="algorithm">The name of the algorithm.</param> public IJwtAlgorithm Create(JwtHashAlgorithm algorithm) { switch (algorithm) { case JwtHashAlgorithm.HS256: return(new HMACSHA256Algorithm()); case JwtHashAlgorithm.HS384: return(new HMACSHA384Algorithm()); case JwtHashAlgorithm.HS512: return(new HMACSHA512Algorithm()); default: throw new InvalidOperationException($"Algorithm {algorithm} is not supported."); } }
/// <summary> /// This method returns the relevant hash algorithm based on the enum type. /// </summary> /// <param name="type">The supported algorithm enum.</param> /// <param name="key">The hash key,</param> /// <returns>Returns the relevant algorithm.</returns> public static HMAC GetAlgorithm(JwtHashAlgorithm type, byte[] key) { switch (type) { case JwtHashAlgorithm.HS256: return(new HMACSHA256(key)); case JwtHashAlgorithm.HS384: return(new HMACSHA384(key)); case JwtHashAlgorithm.HS512: return(new HMACSHA512(key)); default: throw new JwtAlgorithmNotSupportedException(type.ToString()); } }
/// <summary> /// This method creates the necessary signature based on the header and claims passed. /// </summary> /// <param name="algo">The hash algorithm.</param> /// <param name="key">The hash key.</param> /// <param name="joseHeader">The base64 encoded header.</param> /// <param name="jwtClaimsSet">The base64 encoded claims set.</param> /// <returns>Returns the Base64 encoded header.</returns> public static string CalculateAuthSignature(JwtHashAlgorithm algo, byte[] key, string joseHeader, string jwtClaimsSet) { //Thanks to https://jwt.io/ string sig = $"{joseHeader}.{jwtClaimsSet}"; byte[] bySig = Encoding.UTF8.GetBytes(sig); string signature; using (var hashstring = GetAlgorithm(algo, key)) { byte[] sha256Hash = hashstring.ComputeHash(bySig); signature = JwtHelper.SafeBase64UrlEncode(sha256Hash); } return(signature); }
/// <summary> /// This method adds basic Jwt authentication to the web app /// </summary> /// <typeparam name="P">The web pipe type</typeparam> /// <param name="webpipe">The pipe.</param> /// <param name="algo">The supported HMAC algorithm</param> /// <param name="base64Secret">The base64secret</param> /// <param name="audience">The audience value to check.</param> /// <param name="action">The action to be called on the filter creation.</param> /// <param name="removeUnderlyingPrincipal">If this method is set to true, then the principal set from the underlying principal is cleared.</param> /// <returns>Returns the web pipe.</returns> public static P ApiAddJwtTokenAuthentication <P>(this P webpipe , JwtHashAlgorithm algo , string base64Secret , string audience = "api" , Action <IAuthenticationFilter> action = null , bool removeUnderlyingPrincipal = true ) where P : IPipelineWebApi { var policy = new JwtTokenVerificationPolicy { Algorithm = algo , Audience = audience , Secret = Convert.FromBase64String(base64Secret) }; return(webpipe.ApiAddJwtTokenAuthentication(policy, action, removeUnderlyingPrincipal)); }
/// <summary> /// Creates a JWT given a payload, the signing key, and the algorithm to use. /// </summary> /// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param> /// <param name="key">The key bytes used to sign the token.</param> /// <param name="algorithm">The hash algorithm to use.</param> /// <returns>The generated JWT.</returns> public static string Encode(object payload, byte[] key, JwtHashAlgorithm algorithm) { var segments = new List<string>(); var header = new { typ = "JWT", alg = algorithm.ToString() }; byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header)); byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)); segments.Add(Base64UrlEncode(headerBytes)); segments.Add(Base64UrlEncode(payloadBytes)); var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); byte[] signature = HashAlgorithms[algorithm](key, bytesToSign); segments.Add(Base64UrlEncode(signature)); return string.Join(".", segments.ToArray()); }
private bool JwtValidateIncoming(JwtRoot incoming, JwtHashAlgorithm algo, byte[] key) { if (incoming == null) { throw new ArgumentOutOfRangeException("Incoming token not set."); } if (key == null) { throw new ArgumentNullException("key", $"{nameof(JwtValidateIncoming)} - key cannot be null"); } string b64joseHeader = JwtHelper.SafeBase64UrlEncode(incoming.Raw[0]); string b64jwtClaimsSet = JwtHelper.SafeBase64UrlEncode(incoming.Raw[1]); var signed = JwtRoot.CalculateAuthSignature(algo, key, b64joseHeader, b64jwtClaimsSet); var original = JwtHelper.SafeBase64UrlEncode(incoming.Raw[2]); return(original == signed); }
/// <inheritdoc /> public virtual IJwtAlgorithm Create(JwtHashAlgorithm algorithm) { switch (algorithm) { case JwtHashAlgorithm.HS256: return(new HMACSHA256Algorithm()); case JwtHashAlgorithm.HS384: return(new HMACSHA384Algorithm()); case JwtHashAlgorithm.HS512: return(new HMACSHA512Algorithm()); case JwtHashAlgorithm.RS256: throw new NotSupportedException($"For algorithm {nameof(JwtHashAlgorithm.RS256)} please create custom factory by implementing {nameof(IAlgorithmFactory)}"); default: throw new NotSupportedException($"Algorithm {algorithm} is not supported."); } }
/// <summary> /// Creates a JWT given a payload, the signing key, and the algorithm to use. /// </summary> /// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param> /// <param name="key">The key used to sign the token.</param> /// <param name="algorithm">The hash algorithm to use.</param> /// <returns>The generated JWT.</returns> public static string Encode(object payload, byte[] key, JwtHashAlgorithm algorithm) { var segments = new List <string>(); var header = new { typ = "JWT", alg = algorithm.ToString() }; byte[] headerBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(header)); byte[] payloadBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(payload)); segments.Add(Base64UrlEncode(headerBytes)); segments.Add(Base64UrlEncode(payloadBytes)); var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); byte[] signature = HashAlgorithms[algorithm](key, bytesToSign); segments.Add(Base64UrlEncode(signature)); return(string.Join(".", segments.ToArray())); }
public static string Encode(object payload, byte[] key, JwtHashAlgorithm algorithm) { List <string> list = new List <string>(); var obj = new { typ = "JWT", alg = algorithm.ToString() }; byte[] bytes = Encoding.UTF8.GetBytes(JsonWebToken.jsonSerializer.Serialize(obj)); byte[] bytes2 = Encoding.UTF8.GetBytes(JsonWebToken.jsonSerializer.Serialize(payload)); list.Add(JsonWebToken.Base64UrlEncode(bytes)); list.Add(Base64UrlEncode(bytes2)); string s = string.Join(".", list.ToArray()); byte[] bytes3 = Encoding.UTF8.GetBytes(s); byte[] input = HashAlgorithms[algorithm](key, bytes3); list.Add(JsonWebToken.Base64UrlEncode(input)); return(string.Join(".", list.ToArray())); }
/// <summary> /// Encode Data and sign with Certificate /// </summary> /// <param name="payload"></param> /// <param name="keyBytes"></param> /// <param name="algorithm"></param> /// <returns></returns> public static string EncodeUsingCertificate(object payload, RSA keyBytes, JwtHashAlgorithm algorithm) { var segments = new List <string>(); var header = new { alg = algorithm.ToString(), typ = "JWT" }; byte[] headerBytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(header)); byte[] payloadBytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(payload)); segments.Add(Base64UrlEncode(headerBytes)); segments.Add(Base64UrlEncode(payloadBytes)); var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); byte[] signature = HashAlgorithmsSigning[algorithm](keyBytes, bytesToSign); segments.Add(Base64UrlEncode(signature)); return(string.Join(".", segments.ToArray())); }
public static string Encode(object payload, byte[] keyBytes, JwtHashAlgorithm algorithm) { var segments = new List<string>(); var header = new { alg = algorithm.ToString(), typ = "JWT" }; byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Newtonsoft.Json.Formatting.None)); byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Newtonsoft.Json.Formatting.None)); //byte[] payloadBytes = Encoding.UTF8.GetBytes(@"{"iss":"*****@*****.**","scope":"https://www.googleapis.com/auth/prediction","aud":"https://accounts.google.com/o/oauth2/token","exp":1328554385,"iat":1328550785}"); segments.Add(Base64UrlEncode(headerBytes)); segments.Add(Base64UrlEncode(payloadBytes)); var stringToSign = string.Join(".", segments.ToArray()); var bytesToSign = Encoding.UTF8.GetBytes(stringToSign); byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign); segments.Add(Base64UrlEncode(signature)); return string.Join(".", segments.ToArray()); }
/// <summary> /// Creates a JWT given a payload, the signing key, and the algorithm to use. /// </summary> /// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param> /// <param name="key">The key used to sign the token.</param> /// <param name="algorithm">The hash algorithm to use.</param> /// <returns>The generated JWT.</returns> public static string Encode(object payload, string key, JwtHashAlgorithm algorithm) { return Encode(payload, Encoding.UTF8.GetBytes(key), algorithm); }
public JwtSerializer(JwtHashAlgorithm algorithm, int iterations, string salt) { Algorithm = algorithm; Iterations = iterations; Salt = salt; }
public string Encode(object payload, string key, JwtHashAlgorithm algorithm) { return JsonWebToken.Encode(payload, key, algorithm); }