Exemplo n.º 1
0
        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static TokenModelJWT SerializeJWT(string jwtStr)
        {
            var jwtHandler            = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object           role     = new object();
            object           name     = new object();
            object           Exp      = new object();

            try
            {
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
                jwtToken.Payload.TryGetValue(JwtRegisteredClaimNames.GivenName, out name);
                jwtToken.Payload.TryGetValue(JwtRegisteredClaimNames.Exp, out Exp);
            }
            catch (Exception e)
            {
                throw;
            }
            var tm = new TokenModelJWT
            {
                Uid  = jwtToken.Id,
                Role = role != null?role.ToString() : "",
                           UserName                     = name != null?name.ToString() : "",
                                                    Exp = Convert.ToInt64(Exp)
            };

            return(tm);
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </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();
            var tokenHeader = httpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

            try
            {
                if (tokenHeader.Length >= 128)
                {
                    TokenModelJWT tm = JwtHelper.SerializeJWT(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 e)
            {
                Console.WriteLine($"{DateTime.Now} middleware wrong:{e.Message}");
            }


            PostProceed(httpContext);


            return(_next(httpContext));
        }