コード例 #1
0
        /// <summary>
        /// Creates a JWT Token for the given user id using the JWTHeader and JWTBody
        /// classes.
        /// </summary>
        /// <param name="id">The id of the user the </param>
        /// <returns>The token </returns>
        public static string EncodeJWT(int id, UserStatus status)
        {
            JWTBody body = new JWTBody
            {
                Issuer   = AuthorizationInfo.Issuer,
                Audience = AuthorizationInfo.Audience,
                UserID   = id,
                Status   = status,
                Expires  = DateTime.Now + AuthorizationInfo.TokenExpiryTime
            };

            string payload = JsonConvert.SerializeObject(body);

            string basis = Convert.ToBase64String(
                CreateByteArray(JsonConvert.SerializeObject(header))) + "." +
                           Convert.ToBase64String(CreateByteArray(payload));

            HMACMD5 encoder = new HMACMD5(
                CreateByteArray(AuthorizationInfo.SecretKey));

            string signature = Convert.ToBase64String(
                encoder.ComputeHash(CreateByteArray(basis)));

            return(basis + "." + signature);
        }
コード例 #2
0
        /// <summary>
        /// Validates a JDW Token, and determines the user
        /// </summary>
        /// <param name="token"></param>
        /// <param name="id"></param>
        /// <returns>False if token is invalid.</returns>
        public static bool DecodeJWT(string token, out int id, out UserStatus status)
        {
            id     = 0;
            status = UserStatus.Banned;
            string[] parts = token.Split(".".ToArray());

            if (parts.Length != 3)
            {
                return(false);
            }

            HMACMD5 encoder = new HMACMD5(
                CreateByteArray(AuthorizationInfo.SecretKey));

            string signature = Convert.ToBase64String(encoder.ComputeHash(
                                                          CreateByteArray(parts[0] + "." + parts[1])));

            if (signature != parts[2])
            {
                return(false);
            }

            JWTHeader tokenHeader = JsonConvert.DeserializeObject <JWTHeader>(
                Encoding.ASCII.GetString(Convert.FromBase64String(parts[0])));

            if (header == null || !header.Equals(tokenHeader))
            {
                return(false);
            }

            JWTBody tokenBody = JsonConvert.DeserializeObject <JWTBody>(
                Encoding.ASCII.GetString(Convert.FromBase64String(parts[1])));

            if (tokenBody == null ||
                tokenBody.Issuer != AuthorizationInfo.Issuer ||
                tokenBody.Audience != AuthorizationInfo.Audience ||
                tokenBody.Expires < DateTime.Now)
            {
                return(false);
            }

            id     = tokenBody.UserID;
            status = tokenBody.Status;
            return(true);
        }