Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext httpContext)
        {
            //检测是否包含'Authorization'请求头
            if (!httpContext.Request.Headers.ContainsKey("Authorization"))
            {
                return(_next(httpContext));
            }
            //var tokenHeader = httpContext.Request.Headers["Authorization"].ToString();
            var tokenHeader = httpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

            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;
            }

            return(_next(httpContext));
        }
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)
                {
                    JwtTokenModel 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));
        }