Example #1
0
        /// <summary>
        /// 生成用户token信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        JwtTokenInfo GenerateToken(string userCode)
        {
            DateTime     now       = DateTime.Now;
            JwtTokenInfo tokenInfo = new JwtTokenInfo();

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(now.AddMinutes(_jwtSettings.EffectMinutes)).ToUnixTimeSeconds()}"),
                new Claim(ClaimTypes.Name, userCode),
                new Claim(ClaimTypes.Role, "roleAdmin")
            };
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _jwtSettings.Domain,
                audience: _jwtSettings.Domain,
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            tokenInfo.Token    = new JwtSecurityTokenHandler().WriteToken(token);
            tokenInfo.TokenId  = Encrypion.GenerateMD5(tokenInfo.Token);
            tokenInfo.IssuedAt = now;
            tokenInfo.Expires  = now.AddMinutes(_jwtSettings.EffectMinutes);
            tokenInfo.Issuer   = _jwtSettings.Domain;
            return(tokenInfo);
        }
Example #2
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;
            JwtSecurityToken token = parse2Token(securityToken);
            string           md5Id = Encrypion.GenerateMD5(securityToken);
            //给Identity赋值
            ClaimsIdentity identity = null;
            List <Claim>   claims   = new List <Claim>();
            long           nowValue = new DateTimeOffset(TimeHelper.Now).ToUnixTimeSeconds();

            if (token != null)
            {
                string userCode = token.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
                long.TryParse(token.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Nbf).Value, out long nbf);
                long.TryParse(token.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp).Value, out long exp);
                if (!(exp < nowValue || nbf > nowValue))// token的时间非法
                {
                    IUserTokenAppService userService = EngineerContext.Current.Resolve <IUserTokenAppService>();
                    var userTokenInfo = userService.GetTokenById(md5Id);
                    if (userTokenInfo != null && string.Equals(userTokenInfo.Token, securityToken, StringComparison.OrdinalIgnoreCase))
                    {
                        identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                        identity.AddClaims(token.Claims);
                    }
                }
            }
            if (identity == null)
            {
                identity = new ClaimsIdentity("");
            }
            var principle = new ClaimsPrincipal(identity);

            return(principle);
        }
Example #3
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;
            //securityToken = @"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOiIxNTc3NzU5NzcwIiwiZXhwIjoxNTc3NzYxNTcwLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWFhYWFhIiwiaXNzIjoiaHR0cDovL3N1bnl5OS5jb20iLCJhdWQiOiJodHRwOi8vc3VueXk5LmNvbSJ9.jw_L0a4xm3lkdFr1XNtUyDFuCsC1QBVUg9M90ISOWdU";

            //SecurityToken security = new JwtSecurityTokenHandler().ReadToken(securityToken);
            //((JwtSecurityToken)security).Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);

            JwtSecurityToken token = parse2Token(securityToken);
            string           md5Id = Encrypion.GenerateMD5(securityToken);
            //给Identity赋值
            ClaimsIdentity identity = null;
            List <Claim>   claims   = new List <Claim>();
            long           nowValue = new DateTimeOffset(TimeHelper.Now).ToUnixTimeSeconds();

            if (token != null)
            {
                string userCode = token.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
                long.TryParse(token.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Nbf).Value, out long nbf);
                long.TryParse(token.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp).Value, out long exp);
                if (exp < nowValue || nbf > nowValue)// token的时间非法
                {
                    //token过期
                    identity = new ClaimsIdentity("NoPower");
                }
                else
                {
                    //EngineerContext.Current.Resolve<IRepository<UserToken>>();
                }
            }
            else
            {
                identity = new ClaimsIdentity("NoPower");
            }

            identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, "admin"));

            var principle = new ClaimsPrincipal(identity);

            return(principle);
        }