Beispiel #1
0
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="Role"></param>
        public static string GetJwtStr(string userName, string Role)
        {
            string jwtStr = string.Empty;
            //bool suc = false;
            // 获取用户的角色名,请暂时忽略其内部是如何获取的,可以直接用 var userRole="Admin"; 来代替更好理解。
            var userRole = "Admin";

            if (userRole != null)
            {
                // 将用户id和角色名,作为单独的自定义变量封装进 token 字符串中。
                TokenModelJwt tokenModel = new TokenModelJwt {
                    UserName = userName, Role = Role
                };
                // 登录,获取到一定规则的 Token 令牌
                jwtStr = JWTHelper.IssueJwt(tokenModel);
                //suc = true;
            }
            return($"Bearer {jwtStr}");
        }
Beispiel #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)
                {
                    //Console.WriteLine($"{DateTime.Now} token :{tokenHeader}");
                    TokenModelJwt tm = JWTHelper.DeSerializeJwt(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));
        }