Example #1
0
        /// <summary>
        /// 生成JwtToken
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static async Task <LoginParam> GetJwtToken(TokenModelJwt tokenModel)
        {
            string   iss     = ConfigHelper.JwtIssuer;
            string   aud     = ConfigHelper.JwtAudience;
            string   secret  = ConfigHelper.JwtSecret;
            int      overSec = ConfigHelper.JwtOverSec;
            DateTime dtNow   = DateTime.Now;

            List <Claim> claims = GetJwtClaim(tokenModel, iss, aud, overSec, dtNow);

            //秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt        = new JwtSecurityToken(issuer: iss, claims: claims, signingCredentials: creds);
            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            // 保存用户信息到HttpContext.User
            await IdentifyLogin(claims);

            //// 屏蔽,现在Mvc跳转有Cookies认证,没必要保存Jwt Cookie
            //// Jwt授权保存到Cookies
            //StaticHttpContext.Current.Response.Cookies.Append(AuthHelper.JwtAuthName, encodedJwt,
            //    new CookieOptions
            //    {
            //        HttpOnly = true,
            //        Expires = new DateTimeOffset(dtNow).AddSeconds(overSec)
            //    });

            return(new LoginParam
            {
                Token = encodedJwt,
                ExpiresIn = overSec,
                ExpireTimeStamp = new DateTimeOffset(dtNow.AddSeconds(overSec)).ToUnixTimeMilliseconds(),
                UserName = tokenModel.UserName
            });
        }
Example #2
0
        /// <summary>
        /// 验证Jwt授权
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext httpContext)
        {
            PreProceed(httpContext);

            //检测是否包含'Authorization'请求头
            if (!httpContext.Request.Headers.ContainsKey("Authorization"))
            {
                PostProceed(httpContext);
                return(_next(httpContext));
            }

            var tokenHeader = httpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

            try
            {
                if (tokenHeader.Length >= 128)
                {
                    TokenModelJwt tm = AuthHelper.DecryptJwtToken(tokenHeader);

                    //授权
                    //var claimList = new List<Claim>();
                    //var claim = new Claim(ClaimTypes.Role, tm.Role);
                    //claimList.Add(claim);
                    //var identity = new ClaimsIdentity(claimList);
                    //var principal = new ClaimsPrincipal(identity);
                    //httpContext.User = principal;
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"{DateTime.Now} middleware wrong:{e.Message}");
                _logHelper.Error($"JwtTokenAuth:出现异常:{ex.Message}", ex);
            }

            PostProceed(httpContext);
            return(_next(httpContext));
        }