예제 #1
0
 public TokenIssuer()
 {
     _algorithm     = new HMACSHA256Algorithm();
     _serializer    = new JsonNetSerializer();
     _base64Encoder = new JwtBase64UrlEncoder();
     _jwtEncoder    = new JwtEncoder(_algorithm, _serializer, _base64Encoder);
 }
예제 #2
0
 static JwtHelper()
 {
     jwtAlgorithm  = new HMACSHA256Algorithm();
     base64Encrpty = new JwtBase64UrlEncoder();
     serializer    = new JsonNetSerializer();
     provider      = new UtcDateTimeProvider();
 }
예제 #3
0
 static JwtHelper()
 {
     _provider   = new UtcDateTimeProvider();
     _algorithm  = new HMACSHA256Algorithm();
     _serializer = new JsonNetSerializer();
     _urlEncoder = new JwtBase64UrlEncoder();
 }
예제 #4
0
 public TokenMaker()
 {
     algorithm  = new HMACSHA256Algorithm();
     serializer = new JsonNetSerializer();
     urlEncoder = new JwtBase64UrlEncoder();
     encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
 }
예제 #5
0
파일: Token.cs 프로젝트: ferrarienz0/branch
 public Token(Dictionary <string, object> Payload)
 {
     this.Payload        = Payload;
     EncriptionAlgorithm = new HMACSHA256Algorithm();
     JSONSerializer      = new JsonNetSerializer();
     URLEncoder          = new JwtBase64UrlEncoder();
     JWTEncoder          = new JwtEncoder(EncriptionAlgorithm, JSONSerializer, URLEncoder);
 }
예제 #6
0
 public JwtManager(IJwtAlgorithm algorithm      = null, IJsonSerializer serializer = null,
                   IBase64UrlEncoder urlEncoder = null, string secret              = null)
 {
     _builder = new JwtBuilder().WithAlgorithm(algorithm ?? new HMACSHA256Algorithm())
                .WithSerializer(serializer ?? new JsonNetSerializer())
                .WithUrlEncoder(urlEncoder ?? new JwtBase64UrlEncoder())
                .WithSecret(secret ?? Secret);
 }
예제 #7
0
 static SecurityManager()
 {
     _algorithm  = new HMACSHA256Algorithm();
     _serializer = new JsonNetSerializer();
     _urlEncoder = new JwtBase64UrlEncoder();
     _provider   = new UtcDateTimeProvider();
     _validator  = new JwtValidator(_serializer, _provider);
 }
예제 #8
0
 public TokenIssuer()
 {
     // JWT specific initialization.
     // https://github.com/jwt-dotnet/jwt
     _algorithm     = new HMACSHA256Algorithm();
     _serializer    = new JsonNetSerializer();
     _base64Encoder = new JwtBase64UrlEncoder();
     _jwtEncoder    = new JwtEncoder(_algorithm, _serializer, _base64Encoder);
 }
예제 #9
0
 public JWTHelper()
 {
     //非fluent写法
     this._jsonSerializer   = new JsonNetSerializer();
     this._dateTimeProvider = new UtcDateTimeProvider();
     this._jwtValidator     = new JwtValidator(_jsonSerializer, _dateTimeProvider);
     this._base64UrlEncoder = new JwtBase64UrlEncoder();
     this._jwtAlgorithm     = new HMACSHA256Algorithm();
     this._jwtDecoder       = new JwtDecoder(_jsonSerializer, _jwtValidator, _base64UrlEncoder);
     this._jwtEncoder       = new JwtEncoder(_jwtAlgorithm, _jsonSerializer, _base64UrlEncoder);
 }
예제 #10
0
        void init()
        {
            urlEncoder = new JwtBase64UrlEncoder();
            serializer = new JsonNetSerializer();
            algorithm  = new HMACSHA256Algorithm();
            encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            provider  = new UtcDateTimeProvider();
            validator = new JwtValidator(serializer, provider);
            decoder   = new JwtDecoder(serializer, validator, urlEncoder);
        }
예제 #11
0
 public TokenValidationService(IOptions <SecretKeys> secretKeys, ILogger <TokenValidationService> logger)
 {
     _algorithm  = new HMACSHA256Algorithm();
     _serializer = new JsonNetSerializer();
     _provider   = new UtcDateTimeProvider();
     _urlEncoder = new JwtBase64UrlEncoder();
     _validator  = new JwtValidator(_serializer, _provider);
     _decoder    = new JwtDecoder(_serializer, _validator, _urlEncoder, _algorithm);
     _secretKeys = secretKeys;
     _logger     = logger;
 }
예제 #12
0
 public JwtObjectEncoder(JwtSecretOptions jwtSecretOptions)
 {
     secret     = jwtSecretOptions.Secret;
     algorithm  = new HMACSHA256Algorithm();
     serializer = new JsonNetSerializer();
     urlEncoder = new JwtBase64UrlEncoder();
     provider   = new UtcDateTimeProvider();
     validator  = new JwtValidator(serializer, provider);
     encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
     decoder    = new JwtDecoder(serializer, validator, urlEncoder);
 }
예제 #13
0
        static JWTTools()
        {
            algorithm  = new HMACSHA256Algorithm();
            serializer = new JsonNetSerializer();
            urlEncoder = new JwtBase64UrlEncoder();

            encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            provider  = new UtcDateTimeProvider();
            validator = new JwtValidator(serializer, provider);
            decoder   = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
        }
예제 #14
0
        public void Dispose()
        {
            _encoder = null;
            _decoder = null;

            _algorithm  = null;
            _serializer = null;
            _urlEncoder = null;

            _provider  = null;
            _validator = null;
        }
예제 #15
0
        public JWT_Provider()
        {
            _algorithm  = new HMACSHA256Algorithm();
            _serializer = new JsonNetSerializer();
            _urlEncoder = new JwtBase64UrlEncoder();
            _encoder    = new JwtEncoder(_algorithm, _serializer, _urlEncoder);


            _provider  = new UtcDateTimeProvider();
            _validator = new JwtValidator(_serializer, _provider);
            _decoder   = new JwtDecoder(_serializer, _validator, _urlEncoder, _algorithm);
        }
예제 #16
0
 public JwtWriter(IBufferWriter <byte> writer, IJwtAlgorithm algorithm, DateTimeOffset?expire)
 {
     this.writer    = writer;
     this.algorithm = algorithm;
     if (expire != null)
     {
         this.expire = expire.Value.ToUnixTimeSeconds();
     }
     else
     {
         this.expire = null;
     }
 }
 private JwtBuilder GetJwtBuilder(string secret, IJwtAlgorithm algorithm = null)
 {
     if (secret.IsNullOrEmpty())
     {
         throw new AuthException("未设置JwtSecret,请先设置JwtSecret", StatusCode.IssueTokenError);
     }
     if (algorithm == null)
     {
         algorithm = new HMACSHA256Algorithm();
     }
     return(new JwtBuilder()
            .WithAlgorithm(algorithm)
            .WithSecret(secret));
 }
예제 #18
0
        public void InitializerPropertiesTest()
        {
            Mock <IJsonSerializer>   mSerializer   = new Mock <IJsonSerializer>();
            IJsonSerializer          serializer    = mSerializer.Object;
            Mock <IDateTimeProvider> mProvider     = new Mock <IDateTimeProvider>();
            IDateTimeProvider        provider      = mProvider.Object;
            Mock <IJwtValidator>     mValidator    = new Mock <IJwtValidator>();
            IJwtValidator            validator     = mValidator.Object;
            Mock <IBase64UrlEncoder> mUrlEncoder   = new Mock <IBase64UrlEncoder>();
            IBase64UrlEncoder        urlEncoder    = mUrlEncoder.Object;
            Mock <IJwtDecoder>       mDecoder      = new Mock <IJwtDecoder>();
            IJwtDecoder            decoder         = mDecoder.Object;
            Mock <IJwtAlgorithm>   mAlgorithm      = new Mock <IJwtAlgorithm>();
            IJwtAlgorithm          algorithm       = mAlgorithm.Object;
            Mock <IJwtEncoder>     mEncoder        = new Mock <IJwtEncoder>();
            IJwtEncoder            encoder         = mEncoder.Object;
            Mock <ILoggingService> mLoggingService = new Mock <ILoggingService>();
            ILoggingService        loggingService  = mLoggingService.Object;

            using (SecureString secret = _secret.ToSecureString())
                using (JwtServiceArgs args = new JwtServiceArgs(false, null, null)
                {
                    Secret = _secret,
                    SecureSecret = secret,
                    Serializer = serializer,
                    Provider = provider,
                    Validator = validator,
                    UrlEncoder = urlEncoder,
                    Decoder = decoder,
                    Algorithm = algorithm,
                    Encoder = encoder,
                    LoggingService = loggingService
                })
                {
                    Assert.Equal(_secret, args.Secret);
                    Assert.Equal(secret, args.SecureSecret);
                    Assert.Equal(_secret, args.SecureSecret.ToPlainText());
                    Assert.Equal(serializer, args.Serializer);
                    Assert.Equal(provider, args.Provider);
                    Assert.Equal(validator, args.Validator);
                    Assert.Equal(urlEncoder, args.UrlEncoder);
                    Assert.Equal(decoder, args.Decoder);
                    Assert.Equal(algorithm, args.Algorithm);
                    Assert.Equal(encoder, args.Encoder);
                    Assert.Equal(loggingService, args.LoggingService);
                }
        }
예제 #19
0
        public static string JwtEncode(JwtAlgorithmName algorithmName, string secret, IDictionary <string, object> extraHeaders, IDictionary <string, object> payload)
        {
            IJwtAlgorithm algorithm = algorithmName switch
            {
                JwtAlgorithmName.HS256 => new HMACSHA256Algorithm(),
                JwtAlgorithmName.HS384 => new HMACSHA384Algorithm(),
                JwtAlgorithmName.HS512 => new HMACSHA512Algorithm(),
                _ => throw new NotSupportedException("This algorith is not supported at the moment")
            };

            var jsonSerializer = new JsonNetSerializer();
            var urlEncoder     = new JwtBase64UrlEncoder();
            var jwtEncoder     = new JwtEncoder(algorithm, jsonSerializer, urlEncoder);

            return(jwtEncoder.Encode(extraHeaders, payload, secret));
        }

        #endregion
    }
예제 #20
0
        /// <summary>
        /// 解析 JWT Token
        /// </summary>
        /// <param name="secret"></param>
        /// <param name="token"></param>
        /// <param name="principal"></param>
        /// <returns></returns>
        public static bool TryValidateToken(string secret, string token, out ClaimsPrincipal principal)
        {
            principal = null;
            try
            {
                IJsonSerializer              serializer = new JsonNetSerializer();
                IDateTimeProvider            provider   = new UtcDateTimeProvider();
                IJwtValidator                validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder            urlEncoder = new JwtBase64UrlEncoder();
                IJwtAlgorithm                algorithm  = null;
                IJwtDecoder                  decoder    = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                IDictionary <string, object> payload    = decoder.DecodeToObject(token, secret, verify: true);
                List <Claim>                 claims     = new List <Claim>();

                foreach (KeyValuePair <string, object> item in payload)
                {
                    if (item.Value == null)
                    {
                        continue;
                    }

                    string key   = item.Key;
                    string value = item.Value.ToString();
                    claims.Add(new Claim(key, value));
                }
                ClaimsIdentity identity = new ClaimsIdentity(claims, "JWT");
                principal = new ClaimsPrincipal(identity);
                return(true);
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
            }
            return(false);
        }
예제 #21
0
        public static string Encode(string secret, IDictionary <string, object> payload, JwtHashAlgorithm type = JwtHashAlgorithm.HS256)
        {
            HMACSHAAlgorithmFactory factory   = new HMACSHAAlgorithmFactory();
            IJwtAlgorithm           algorithm = factory.Create(type);

            JWT.IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder   urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder         encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
            var builder = new JwtBuilder()
                          .WithAlgorithm(algorithm)
                          .WithSecret(secret);

            if (payload != null)
            {
                foreach (var key in payload.Keys)
                {
                    builder = builder.AddClaim(key, payload[key]);
                }
            }
            var token = builder.Build();

            return(token);
        }
예제 #22
0
        public void SignIn(TBody body)
        {
            //  获取 密钥
            string secret = SecretBuilder.Build();

            if (string.IsNullOrWhiteSpace(secret))
            {
                throw new Exception("应用程序密钥(AppSecret)为空或null");
            }

            //  生成加密token;
            IAlgorithmFactory algorithmFactory = new HMACSHAAlgorithmFactory();
            IJwtAlgorithm     algorithm        = algorithmFactory.Create(AuthConfigProvider.AuthConfig.JwtAlgorithmType);
            IJsonSerializer   serializer       = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder       = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder          = new JwtEncoder(algorithm, serializer, urlEncoder);
            string            token            = encoder.Encode(body, secret);

            //  写入Cookie
            ICookieFactory cookieFactory = new CookieFactory();
            ICookieClient  cookieClient  = cookieFactory.Create();

            cookieClient.SetCookie(AuthConfigProvider.AuthConfig.CookieName, token, AuthConfigProvider.AuthConfig.Expires);
        }
예제 #23
0
 /// <summary>
 /// Sets JWT algorithm.
 /// </summary>
 /// <returns>Current builder instance.</returns>
 public JwtBuilder WithAlgorithm(IJwtAlgorithm algorithm)
 {
     _algorithm = algorithm;
     return(this);
 }
예제 #24
0
 public JwtEncoder(IJwtAlgorithm algorithm, IJsonSerializer jsonSerializer)
 {
     _algorithm      = algorithm;
     _jsonSerializer = jsonSerializer;
 }
예제 #25
0
 public JwtEncoder(IJwtAlgorithm signAlgorithm)
 {
     this.signAlgorithm = signAlgorithm;
 }
예제 #26
0
 /// <summary>
 /// Creates an instance of <see cref="JwtDecoder" />
 /// </summary>
 /// <param name="jsonSerializer">The Json Serializer</param>
 /// <param name="jwtValidator">The Jwt validator</param>
 /// <param name="urlEncoder">The Base64 URL Encoder</param>
 /// <param name="algorithm">The Algorithm</param>
 public JwtDecoder(IJsonSerializer jsonSerializer, IJwtValidator jwtValidator, IBase64UrlEncoder urlEncoder, IJwtAlgorithm algorithm)
     : this(jsonSerializer, jwtValidator, urlEncoder, new DelegateAlgorithmFactory(algorithm))
 {
 }
예제 #27
0
        /// <summary>
        /// Encode object with secret
        /// </summary>
        /// <param name="secretToken"></param>
        /// <param name="objectToEncode"></param>
        /// <returns></returns>
        public OutputDto <string> Encode(string secretToken, object objectToEncode, DateTime?tokenExpireDate = null, IJwtAlgorithm algorithm = null)
        {
            try
            {
                //Add 1 hour of token expiration by default
                DateTimeOffset expireDate = DateTimeOffset.UtcNow.AddHours(1);

                //Add default algorithm
                if (algorithm == null)
                {
                    algorithm = new HMACSHA256Algorithm();
                }

                //Encode token
                var tokenBuilder = new JwtBuilder()
                                   .WithAlgorithm(algorithm)
                                   .WithSecret(secretToken)
                                   .AddClaim("content", objectToEncode);

                //Validate expire date
                if (tokenExpireDate.HasValue)
                {
                    //Parse date to UTC
                    expireDate = tokenExpireDate.Value.Kind != DateTimeKind.Utc ? tokenExpireDate.Value.ToUniversalTime() : tokenExpireDate.Value;

                    tokenBuilder = tokenBuilder.AddClaim("exp", expireDate.ToUnixTimeSeconds());
                }

                //Build token
                var token = tokenBuilder.Build();

                //Validate token
                if (string.IsNullOrWhiteSpace(token))
                {
                    return(new OutputDto <string>(HttpStatusCode.Unauthorized, "The generated token is empty", null));
                }

                if (tokenExpireDate.HasValue)
                {
                    //Return converted Object
                    return(new OutputDto <string>(token, HttpStatusCode.OK, ToUtc(expireDate.DateTime)));
                }
                else
                {
                    return(new OutputDto <string>(token));
                }
            }
            catch (Exception ex)
            {
                return(new OutputDto <string>(HttpStatusCode.Unauthorized, ex.ToString()));
            }
        }
예제 #28
0
 /// <summary>
 /// Returns whether or not the algorithm is asymmetric.
 /// </summary>
 /// <param name="alg">The algorithm instance.</param>
 public static bool IsAsymmetric(this IJwtAlgorithm alg) =>
 alg is IAsymmetricAlgorithm;
예제 #29
0
 /// <summary>
 /// Creates an instance of <see cref="JwtEncoder" />
 /// </summary>
 /// <param name="jsonSerializer">The Json Serializer</param>
 /// <param name="algorithm">The Jwt Algorithm</param>
 /// <param name="urlEncoder">The Base64 URL Encoder</param>
 public JwtEncoder(IJwtAlgorithm algorithm, IJsonSerializer jsonSerializer, IBase64UrlEncoder urlEncoder)
 {
     _algorithm      = algorithm;
     _jsonSerializer = jsonSerializer;
     _urlEncoder     = urlEncoder;
 }
예제 #30
0
        public DecodeResult TryDecode <T>(ReadOnlySpan <char> token, PayloadParser <T> payloadParser, out T payloadResult)
        {
            Split(token, out var header, out var payload, out var headerAndPayload, out var signature);

            IJwtAlgorithm algorithm = null;

            // parsing header.
            {
                Span <byte> bytes = stackalloc byte[Base64.GetMaxBase64UrlDecodeLength(header.Length)];
                if (!Base64.TryFromBase64UrlChars(header, bytes, out var bytesWritten))
                {
                    payloadResult = default;
                    return(DecodeResult.InvalidBase64UrlHeader);
                }

                var reader = new JsonReader(bytes.Slice(0, bytesWritten));
                var count  = 0;
                while (reader.ReadIsInObject(ref count))
                {
                    // try to read algorithm span.
                    if (reader.ReadPropertyNameSegmentRaw().SequenceEqual(JwtConstantsUtf8.Algorithm))
                    {
                        algorithm = resolver.Resolve(reader.ReadStringSegmentRaw());
                    }
                    else
                    {
                        reader.ReadNextBlock();
                    }
                }
            }

            // parsing payload.
            long?expiry    = null;
            long?notBefore = null;

            {
                var rentBytes = ArrayPool <byte> .Shared.Rent(Base64.GetMaxBase64UrlDecodeLength(payload.Length));

                try
                {
                    Span <byte> bytes = rentBytes.AsSpan();
                    if (!Base64.TryFromBase64UrlChars(payload, bytes, out var bytesWritten))
                    {
                        payloadResult = default;
                        return(DecodeResult.InvalidBase64UrlPayload);
                    }

                    var decodedPayload = bytes.Slice(0, bytesWritten);

                    var reader = new JsonReader(decodedPayload);
                    var count  = 0;
                    while (reader.ReadIsInObject(ref count))
                    {
                        // try to read algorithm span.
                        var rawSegment = reader.ReadPropertyNameSegmentRaw();
                        if (rawSegment.SequenceEqual(JwtConstantsUtf8.Expiration))
                        {
                            expiry = reader.ReadInt64();
                        }
                        else if (rawSegment.SequenceEqual(JwtConstantsUtf8.NotBefore))
                        {
                            notBefore = reader.ReadInt64();
                        }
                        else
                        {
                            reader.ReadNextBlock();
                        }
                    }

                    // and custom deserialize.
                    payloadResult = payloadParser(decodedPayload);
                }
                finally
                {
                    ArrayPool <byte> .Shared.Return(rentBytes);
                }
            }
            if (expiry != null)
            {
                var now        = DateTimeOffset.UtcNow;
                var expireTime = DateTimeOffset.FromUnixTimeSeconds(expiry.Value);
                if (expireTime - now < TimeSpan.Zero)
                {
                    return(DecodeResult.FailedVerifyExpire);
                }
            }
            if (notBefore != null)
            {
                var now           = DateTimeOffset.UtcNow;
                var notBeforeTime = DateTimeOffset.FromUnixTimeSeconds(notBefore.Value);
                if (now - notBeforeTime < TimeSpan.Zero)
                {
                    return(DecodeResult.FailedVerifyNotBefore);
                }
            }

            // parsing signature.
            {
                if (algorithm == null)
                {
                    return(DecodeResult.AlgorithmNotExists);
                }

                var rentBuffer = ArrayPool <byte> .Shared.Rent(Encoding.UTF8.GetMaxByteCount(headerAndPayload.Length));

                try
                {
                    Span <byte> signatureDecoded = stackalloc byte[Base64.GetMaxBase64UrlDecodeLength(signature.Length)];
                    if (!Base64.TryFromBase64UrlChars(signature, signatureDecoded, out var bytesWritten))
                    {
                        return(DecodeResult.InvalidBase64UrlSignature);
                    }
                    signatureDecoded = signatureDecoded.Slice(0, bytesWritten);

                    var signBuffer = rentBuffer.AsSpan();
                    var byteCount  = Encoding.UTF8.GetBytes(headerAndPayload, signBuffer);
                    signBuffer = signBuffer.Slice(0, byteCount);
                    if (!algorithm.Verify(signBuffer, signatureDecoded))
                    {
                        return(DecodeResult.FailedVerifySignature);
                    }
                }
                finally
                {
                    ArrayPool <byte> .Shared.Return(rentBuffer);
                }
            }

            // all ok
            return(DecodeResult.Success);
        }