Beispiel #1
0
        //public static string Encode(object payload, string key, JwtAlgorithm algorithm)
        //{
        //    return Encode(payload, key, algorithm);
        //}

        public static string Encode(object payload, string key, JwtAlgorithm algorithm, string headerAlgCus = null, string headerKeyId = null)
        {
            var segments = new List <string>();
            //var header = new { alg = algorithm.ToString(), typ = "JWT" };

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
            {
                Formatting        = Formatting.None,
                NullValueHandling = NullValueHandling.Ignore
            };

            byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { typ = "JWT", kid = headerKeyId, alg = algorithm.ToString(), cus = headerAlgCus }, jsonSerializerSettings));

            byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, jsonSerializerSettings));
            //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 = null;

            signature = HashComputeAlgorithms[algorithm](key, bytesToSign);

            segments.Add(Base64UrlEncode(signature));

            return(string.Join(".", segments.ToArray()));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="JwtToken"/> class
 /// </summary>
 /// <param name="algorithm"><c>jwt</c> signing algorithm</param>
 /// <param name="claims"><c>jwt</c> claims</param>
 public JwtToken(JwtAlgorithm algorithm, JwtClaims claims)
 {
     this.Algorithm = algorithm;
     this.Claims    = claims;
     this.InitializeHeaderAndPayload();
 }