コード例 #1
0
        /// <summary>
        /// Gets the access token of an user that associate with a session and return a JSON Web Token
        /// </summary>
        /// <param name="userID">The string that presents the identity of the user</param>
        /// <param name="sessionID">The string that presents the identity of the associated session</param>
        /// <param name="roles">The collection that presents the roles that the user was belong to</param>
        /// <param name="privileges">The collection that presents the access privileges that the user was got</param>
        /// <param name="key">The key used to encrypt and sign</param>
        /// <param name="onCompleted">The action to run to modify playload (if needed) when the processing is completed</param>
        /// <param name="hashAlgorithm">The hash algorithm used to hash and sign (md5, sha1, sha256, sha384, sha512, ripemd/ripemd160, blake128, blake/blake256, blake384, blake512)</param>
        /// <returns>A JSON Web Token that presents the access token</returns>
        public static string GetAccessToken(string userID, string sessionID, IEnumerable <string> roles, IEnumerable <Privilege> privileges, BigInteger key, Action <JObject> onCompleted = null, string hashAlgorithm = "BLAKE256")
        {
            var token = new JObject
            {
                { "jti", sessionID },
                { "uid", userID },
                { "rls", (roles ?? new List <string>()).Distinct(StringComparer.OrdinalIgnoreCase).ToJArray() },
                { "pls", (privileges ?? new List <Privilege>()).ToJArray() }
            }.ToString(Formatting.None);
            var hash      = token.GetHash(hashAlgorithm);
            var signature = key.Sign(hash);
            var publicKey = key.GenerateECCPublicKey();
            var payload   = new JObject
            {
                { "iat", DateTime.Now.ToUnixTimestamp() },
                { "exp", DateTime.Now.AddDays(90).ToUnixTimestamp() },
                { "nbf", DateTime.Now.AddDays(-30).ToUnixTimestamp() },
                { "jti", publicKey.Encrypt(sessionID.HexToBytes()).ToHex() },
                { "uid", userID },
                { "atk", publicKey.Encrypt(token, true) },
                { "ath", hash.ToHex() },
                { "sig", ECCsecp256k1.GetSignature(signature) }
            };

            onCompleted?.Invoke(payload);
            return(JSONWebToken.Encode(payload, ECCsecp256k1.GetPublicKey(publicKey).ToHex(), hashAlgorithm));
        }
コード例 #2
0
        /// <summary>
        /// Parses the given access token and return an <see cref="User">User</see> object
        /// </summary>
        /// <param name="accessToken">The JSON Web Token that presents the access token</param>
        /// <param name="key">The key used to decrypt and verify</param>
        /// <param name="onCompleted">The action to run to update user information (if needed) when the processing is completed</param>
        /// <param name="hashAlgorithm">The hash algorithm used to hash and sign (md5, sha1, sha256, sha384, sha512, ripemd/ripemd160, blake128, blake/blake256, blake384, blake512)</param>
        /// <returns>The <see cref="User">User</see> object that presented by the access token</returns>
        public static User ParseAccessToken(this string accessToken, BigInteger key, Action <JObject, User> onCompleted = null, string hashAlgorithm = "BLAKE256")
        {
            try
            {
                // decode JSON Web Token
                var publicKey = key.GenerateECCPublicKey();
                var payload   = JSONWebToken.DecodeAsJson(accessToken, ECCsecp256k1.GetPublicKey(publicKey).ToHex());
                var token     = payload.ToExpandoObject();

                // times
                var issuedAt  = token.Get <long>("iat").FromUnixTimestamp();
                var expiresAt = token.Get <long>("exp").FromUnixTimestamp();
                var notBefore = token.Get <long>("nbf").FromUnixTimestamp();
                if (DateTime.Now > expiresAt || DateTime.Now < notBefore || issuedAt > expiresAt || issuedAt < notBefore)
                {
                    throw new TokenExpiredException();
                }

                // identities
                var tokenID = token.Get <string>("jti");
                var userID  = token.Get <string>("uid");
                if (string.IsNullOrWhiteSpace(tokenID) || string.IsNullOrWhiteSpace(userID))
                {
                    throw new InvalidTokenException("Invalid identity");
                }
                else
                {
                    tokenID = key.Decrypt(tokenID.HexToBytes()).ToHex();
                }

                // signature
                var hash      = token.Get <string>("ath").HexToBytes();
                var signature = ECCsecp256k1.GetSignature(token.Get <string>("sig"));
                if (!publicKey.Verify(hash, signature))
                {
                    throw new InvalidTokenSignatureException();
                }

                accessToken = key.Decrypt(token.Get <string>("atk"), true);
                if (!hash.SequenceEqual(accessToken.GetHash(hashAlgorithm)))
                {
                    throw new InvalidTokenException("Not matched");
                }

                // info of access token
                token = accessToken.ToExpandoObject();
                if (!userID.IsEquals(token.Get <string>("uid")) || !tokenID.IsEquals(token.Get <string>("jti")))
                {
                    throw new InvalidTokenException("Invalid identity");
                }

                var roles      = token.Get <List <string> >("rls");
                var privileges = token.Get <List <Privilege> >("pls");

                // create new user identity
                var user = new User(userID, tokenID, roles, privileges);

                // callback
                onCompleted?.Invoke(payload, user);

                // return user identity
                return(user);
            }
            catch (Exception ex)
            {
                if (ex is TokenExpiredException || ex is InvalidTokenSignatureException || ex is InvalidTokenException)
                {
                    throw;
                }
                throw new InvalidTokenException("Invalid access token", ex);
            }
        }