//public UserAuthorizeMiddleware(RequestDelegate next, AuthServerConfig authServerConfig, IServiceProvider  serviceProvider)
        //{
        //    if (next == null)
        //    {
        //        throw new ArgumentNullException(nameof(next));
        //    }
        //    _next = next;
        //    _authServerConfig = authServerConfig;
        //    _serviceProvider = serviceProvider;
        //    var _emailRepository = serviceProvider.GetRequiredService<IHttpClientFactoryHelper>();
        //}
        /// <summary>
        /// Scoped的接口只能从Invoke进行方法注入,否则无法获取到对象
        /// </summary>
        /// <param name="context"></param>
        /// <param name="httpRequest"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context, IHttpClientFactoryHelper httpClient)
        {
            string token = string.Empty;

            token = context.Request.Headers["Authorization"];//先从请求头获取token
            if (string.IsNullOrEmpty(token))
            {
                token = context.Session.GetString("token");//再从session中获取token
            }

            string             url                = $"{_authServerConfig.TokenServerUrl}/Security/Token/ValidateToken";
            string             posData            = JsonConvert.SerializeObject(token);
            TokenAuthorizeInfo tokenAuthorizeInfo = await httpClient.GetJsonResult <TokenAuthorizeInfo>(url, posData, HttpMethod.Get);

            if (tokenAuthorizeInfo != null)
            {
                if (tokenAuthorizeInfo.Status)
                {
                    await _next(context);
                }
                else
                {
                    context.Response.StatusCode = 401;
                }
            }
            else
            {
                context.Response.StatusCode = 401;
            }
        }
예제 #2
0
        /// <summary>
        /// 登录并获取token
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public TokenAuthorizeInfo LoginAndGetToken(LoginUserMode userModel)
        {
            UserInfo           userInfo;
            TokenAuthorizeInfo tokenAuthorizeInfo = new TokenAuthorizeInfo();

            userInfo = _userService.QueryableToEntity(x => x.user_name.Equals(userModel.user_name));
            if (userInfo == null)
            {
                tokenAuthorizeInfo.ErrorMessage = "未查找到用户";
            }
            else if (!userInfo.user_pwd.DecodeBase64().Equals(userModel.user_pwd))
            {
                tokenAuthorizeInfo.ErrorMessage = "用户密码错误";
            }
            else
            {
                tokenAuthorizeInfo.Status        = true;
                tokenAuthorizeInfo.AuthorizeType = "Bearer";
                tokenAuthorizeInfo.UserId        = userInfo.id;
                tokenAuthorizeInfo.UserName      = userInfo.user_name;
                tokenAuthorizeInfo.Token         = _tokenService.GetToken(userInfo);
                tokenAuthorizeInfo.ValidTime     = DateTime.Now.AddMinutes(_tokenService.TokenSetting.ExpireMins);

                userInfo.last_login = DateTime.Now;
                _userService.Update(userInfo);//更新最后一次登录时间
            }

            return(tokenAuthorizeInfo);
        }
예제 #3
0
        /// <summary>
        /// 解析Token
        /// </summary>
        /// <param name="AuthToken"></param>
        /// <returns></returns>
        public TokenAuthorizeInfo ValidateToken(string AuthToken)
        {
            DateTime           ValidTime;
            TokenAuthorizeInfo tokenInfo = new TokenAuthorizeInfo();

            if (string.IsNullOrEmpty(AuthToken) == false)
            {
                var           tokenHandler         = new JwtSecurityTokenHandler();
                var           validationParameters = GetValidationParameters();
                SecurityToken validatedToken;
                try
                {
                    ClaimsPrincipal  principal        = tokenHandler.ValidateToken(AuthToken, validationParameters, out validatedToken);
                    JwtSecurityToken JwtVlidatedToken = validatedToken as JwtSecurityToken;
                    ValidTime = validatedToken.ValidTo.AddHours(8);//时区为零时区,需要加8小时

                    Claim claim = JwtVlidatedToken.Claims.First(x => x.Type.Equals("name"));
                    if (claim != null)
                    {
                        tokenInfo.UserName  = claim.Value;
                        tokenInfo.ValidTime = ValidTime;
                        tokenInfo.Status    = true;
                    }
                    else
                    {
                        tokenInfo.ErrorMessage = "错误,Token不含用户名称";
                    }
                }
                catch (Exception ex)//token过期会自动报错
                {
                    tokenInfo.ErrorMessage = "错误,Token解析失败" + ex.Message;
                }
            }
            return(tokenInfo);
        }
        public async Task <string> GetTokenAsync(string UserJsonString, CancellationToken cancellationToken)
        {
            LoginUserMode      user = JsonConvert.DeserializeObject <LoginUserMode>(UserJsonString);
            TokenAuthorizeInfo tokenAuthorizeInfo = _userLoginService.LoginAndGetToken(user);
            string             ResponseJson       = JsonConvert.SerializeObject(tokenAuthorizeInfo);

            return(ResponseJson);
        }
            public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                string token = string.Empty;

                token = context.HttpContext.Request.Headers["Authorization"];//先从请求头获取token
                if (string.IsNullOrEmpty(token))
                {
                    token = context.HttpContext.Session.GetString("token");//再从session中获取token
                }

                var                objectResult       = context.Result as ObjectResult;
                string             url                = $"{_authServerConfig.TokenServerUrl}/security/Token/ValidateToken";
                string             posData            = JsonConvert.SerializeObject(token);
                TokenAuthorizeInfo tokenAuthorizeInfo = await _httpClient.GetJsonResult <TokenAuthorizeInfo>(url, posData, HttpMethod.Get);

                if (tokenAuthorizeInfo != null)
                {
                    if (tokenAuthorizeInfo.Status)
                    {
                        //continue;
                        //context.Result = objectResult;
                        await next.Invoke();
                    }
                    else
                    {
                        if (_IsRedirectToLogin)
                        {
                            context.HttpContext.Response.StatusCode = 401;
                            context.Result = new RedirectResult(_authServerConfig.LoginUrl);//跳转到登录页面
                        }
                        else
                        {
                            objectResult   = new ObjectResult(new { code = 401, msg = "用户未有授权" });
                            context.Result = objectResult;
                            context.HttpContext.Response.StatusCode = 401;
                        }
                    }
                }
                else
                {
                    if (_IsRedirectToLogin)
                    {
                        context.HttpContext.Response.StatusCode = 401;
                        context.Result = new RedirectResult(_authServerConfig.LoginUrl);//跳转到登录页面
                    }
                    else
                    {
                        objectResult   = new ObjectResult(new { code = 401, msg = "用户未有授权" });
                        context.Result = objectResult;
                        context.HttpContext.Response.StatusCode = 401;
                    }
                }
            }
        public IActionResult ValidateToken()//验证token结果
        {
            TokenAuthorizeInfo tokenParseResult = new TokenAuthorizeInfo();

            if (HttpContext.Request.Headers.ContainsKey("Authorization"))
            {
                string token = HttpContext.Request.Headers["Authorization"];
                tokenParseResult = _tokenService.ValidateToken(token);
            }

            return(new JsonResult(tokenParseResult));
        }
예제 #7
0
        public IActionResult ValidateToken([FromBody] string AuthToken)//验证token结果
        {
            string token = AuthToken;

            if (token.Contains("Bearer"))
            {
                token = token.Replace("Bearer", string.Empty);
                token = token.Trim();
            }
            _logWrite.WriteLog("Token", "ValidateToken", "请求验证token");
            TokenAuthorizeInfo tokenParseResult = _tokenService.ValidateToken(token);

            return(new JsonResult(tokenParseResult));
        }
예제 #8
0
        public async Task <IActionResult> LoginAsync(string name, string password)
        {
            string             url = "http://172.21.168.5:8010/Authentication/Token/GetToken?name=admin&password=admin";
            TokenAuthorizeInfo tokenAuthorizeInfo = await _httpClient.GetJsonResult <TokenAuthorizeInfo>(url, null, HttpMethod.Get);

            if (tokenAuthorizeInfo != null)
            {
                var _session = _httpContextAccessor.HttpContext.Session;
                _session.SetString("user_name", tokenAuthorizeInfo.UserName);
                _session.SetString("token", tokenAuthorizeInfo.Token);
                return(Content("OK"));
            }

            return(Content("Fail"));
        }
예제 #9
0
        public IActionResult ValidhHeaderToken()//验证token结果
        {
            TokenAuthorizeInfo tokenParseResult = new TokenAuthorizeInfo();

            if (HttpContext.Request.Headers.ContainsKey("Authorization"))
            {
                string token = HttpContext.Request.Headers["Authorization"];
                if (token.Contains("Bearer"))
                {
                    token = token.Replace("Bearer", string.Empty);
                    token = token.Trim();
                }
                _logWrite.WriteLog("Token", "ValidhHeaderToken", "请求验证token");
                tokenParseResult = _tokenService.ValidateToken(token);
            }

            return(new JsonResult(tokenParseResult));
        }
예제 #10
0
        public async Task <string> GetTokenAsync(string UserJsonString, CancellationToken cancellationToken)
        {
            TokenAuthorizeInfo tokenAuthorizeInfo = new TokenAuthorizeInfo();
            UserInfo           user = JsonConvert.DeserializeObject <UserInfo>(UserJsonString);

            if (user.user_name != "admin" && user.user_pwd != "admin")//此代码临时处理,因为用户权限功能暂时无
            {
                user = _userService.QueryableToEntity(x => x.user_name.Equals(user.user_name));
                if (user == null)
                {
                    tokenAuthorizeInfo.ErrorMessage = "未查找到用户";
                }
                else if (!user.user_pwd.DecodeBase64().Equals(user.user_pwd))
                {
                    tokenAuthorizeInfo.ErrorMessage = "用户密码错误";
                }
            }
            else
            {
                user = new UserInfo()
                {
                    id = 1, user_name = "admin"
                };
            }

            if (user != null && user.id > 0)
            {
                tokenAuthorizeInfo.AuthorizeType = "Bearer";
                tokenAuthorizeInfo.UserId        = user.id;
                tokenAuthorizeInfo.UserName      = user.user_name;
                tokenAuthorizeInfo.Token         = _tokenService.GetToken(user);
                tokenAuthorizeInfo.ValidTime     = DateTime.Now.AddMinutes(_tokenService.TokenSetting.ExpireMins);
            }

            string ResponseJson = JsonConvert.SerializeObject(tokenAuthorizeInfo);

            return(ResponseJson);
        }
예제 #11
0
        public IActionResult GetToken(string name, string password)
        {
            UserInfo           user;
            TokenAuthorizeInfo tokenAuthorizeInfo = new TokenAuthorizeInfo();

            if (name != "admin" && password != "admin")//此代码临时处理,因为用户权限功能暂时无
            {
                user = _userService.QueryableToEntity(x => x.user_name.Equals(name));
                if (user == null)
                {
                    tokenAuthorizeInfo.ErrorMessage = "未查找到用户";
                }
                else if (!user.user_pwd.DecodeBase64().Equals(password))
                {
                    tokenAuthorizeInfo.ErrorMessage = "用户密码错误";
                }
            }
            else
            {
                user = new UserInfo()
                {
                    id = 1, user_name = "admin"
                };
            }

            if (user != null && user.id > 0)
            {
                tokenAuthorizeInfo.AuthorizeType = "Bearer";
                tokenAuthorizeInfo.UserId        = user.id;
                tokenAuthorizeInfo.UserName      = user.user_name;
                tokenAuthorizeInfo.Token         = _tokenService.GetToken(user);
                tokenAuthorizeInfo.ValidTime     = DateTime.Now.AddMinutes(_tokenService.TokenSetting.ExpireMins);
            }
            return(new JsonResult(tokenAuthorizeInfo));
            // return JsonConvert.SerializeObject(tokenAuthorizeInfo);
        }
예제 #12
0
        public IActionResult ValidateToken(string AuthToken)//验证token结果
        {
            TokenAuthorizeInfo tokenParseResult = _tokenService.ValidateToken(AuthToken);

            return(new JsonResult(tokenParseResult));
        }
예제 #13
0
        public async Task <string> ValidateTokenAsync(string AuthToken, CancellationToken cancellationToken)
        {
            TokenAuthorizeInfo tokenInfo = _tokenService.ValidateToken(AuthToken);

            return(JsonConvert.SerializeObject(tokenInfo));
        }
예제 #14
0
        public IActionResult Login([FromBody] LoginUserMode userModel)
        {
            TokenAuthorizeInfo tokenAuthorizeInfo = _userLoginService.LoginAndGetToken(userModel);

            return(new JsonResult(tokenAuthorizeInfo));
        }