/// <summary>
        /// 获取JWT字符串并存入缓存
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <param name="expiresSliding"></param>
        /// <param name="expiresAbsolute"></param>
        /// <returns></returns>
        public static string IssueJWT(TokenModel tokenModel, TimeSpan expiresSliding, TimeSpan expiresAbsolute)
        {
            DateTime dtUTC = DateTime.UtcNow;

            Claim[] claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, tokenModel.Sub),                              //subject
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),                   //JWT ID,JWT唯一标识
                new Claim(JwtRegisteredClaimNames.Iat, dtUTC.ToString(), ClaimValueTypes.Integer64), //Issued At,JWT颁发的时间,采用标准unix时间,用于验证过期
            };

            JwtSecurityToken jwt = new JwtSecurityToken(
                issuer: "NetCoreTest",       //jwt签发者,非必须,自定义
                audience: tokenModel.Uname,  //jwt的接收方,非必须
                claims: claims,              //声明集合
                expires: dtUTC.AddHours(12), //指定token的生命周期,unix时间戳格式,非必须
                signingCredentials: new Microsoft.IdentityModel.Tokens.
                SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("NetCoreTest's Secret Key")),
                                   SecurityAlgorithms.HmacSha256)
                );

            var encodedJWT = new JwtSecurityTokenHandler().WriteToken(jwt);

            NetCoreMemoryCache.AddMemoryCache(encodedJWT, tokenModel, expiresSliding, expiresAbsolute);//将JWT字符串,令牌实体,存入缓存

            return(encodedJWT);
        }
Beispiel #2
0
        /// <summary>
        /// 验证授权
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext httpContext)
        {
            var headers = httpContext.Request.Headers;

            //检测是否包含'Authorization'请求头,如果不包含返回context进行下一个中间件,用于访问不需要认证的API
            if (!headers.ContainsKey("Authorization"))
            {
                return(_next(httpContext));
            }

            var tokenStr = headers["Authorization"];

            try
            {
                string jwtStr = tokenStr.ToString().Trim();

                //如果存在Authorization,但是和缓存的不一样,那就是被篡改了
                if (!NetCoreMemoryCache.Exists(jwtStr))
                {
                    return(httpContext.Response.WriteAsync("非法请求"));
                }

                TokenModel tm = (TokenModel)NetCoreMemoryCache.Get(jwtStr);

                //提取tokenModel中的Sub属性进行authorize认证
                List <Claim> lc = new List <Claim>();
                Claim        c  = new Claim(tm.Sub + "Type", tm.Sub);
                lc.Add(c);

                ClaimsIdentity  identity  = new ClaimsIdentity(lc);
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                httpContext.User = principal;

                return(_next(httpContext));
            }
            catch (Exception)
            {
                return(httpContext.Response.WriteAsync("token验证异常"));
            }
        }