public void OnActionExecuted(ActionExecutedContext context) { var requestId = context.ActionDescriptor.Id; var MonLog = _Cache.Get <MonitorLog>(requestId); if (MonLog != null) { MonLog.ExecuteEndTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo)); var mm = (MonLog.ExecuteEndTime - MonLog.ExecuteStartTime); MonLog.TimeConsuming = Convert.ToDecimal((MonLog.ExecuteEndTime - MonLog.ExecuteStartTime).TotalSeconds); logger.LogInformation(MonLog.GetLoginfo()); //插入表 var m_dict = ActionType(MonLog.ActionName); SysLog m_log = new SysLog(); m_log.Id = Guid.NewGuid().GuidTo16String(); m_log.MId = MonLog.UID; m_log.NId = MonLog.NId; m_log.RoleId = m_dict.Id; m_log.CreateTime = MonLog.ExecuteEndTime; m_log.ExecuteTime = MonLog.TimeConsuming; m_log.LoginIp = context.HttpContext.Connection.RemoteIpAddress.ToString(); m_log.FromBady = MonLog.BodyCollections; m_log.UrlParam = MonLog.QueryCollections.ToString(); if (m_log.NId != null) { _SysLogService.AddAsync(m_log); } } }
public async Task <IActionResult> Login([FromBody] SysAdminLogin parm) { var apiRes = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; var token = ""; try { //获得公钥私钥,解密 var rsaKey = MemoryCacheService.Default.GetCache <List <string> >("LOGINKEY"); if (rsaKey == null) { apiRes.message = "登录失败,请刷新浏览器再次登录"; return(Ok(apiRes)); } //Ras解密密码 var ras = new RSACrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(ConfigExtensions.Configuration[KeyHelper.LOGINCOUNT]); //获得登录次数和过期时间 var loginConfig = MemoryCacheService.Default.GetCache <SysAdminLoginConfig>(KeyHelper.LOGINCOUNT) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { apiRes.message = "您的登录以超过设定次数,请稍后再次登录~"; return(Ok(apiRes)); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } //查询登录结果 var dbres = await _adminService.LoginAsync(parm); if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(ConfigExtensions.Configuration[KeyHelper.LOGINDELAYMINUTE]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); apiRes.message = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(Ok(apiRes)); } //记录登录次数,保存到session MemoryCacheService.Default.SetCache(KeyHelper.LOGINCOUNT, loginConfig); //提示用户错误和登录次数信息 apiRes.message = dbres.message + " 您还剩余" + (configLoginCount - loginConfig.Count) + "登录次数"; return(Ok(apiRes)); } var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, user.Guid), new Claim(ClaimTypes.Role, user.DepartmentName), new Claim(ClaimTypes.Thumbprint, user.HeadPic), new Claim(ClaimTypes.Name, user.LoginName), new Claim(ClaimTypes.WindowsAccountName, user.LoginName), new Claim(ClaimTypes.UserData, user.UpLoginDate.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); //如果保存用户类型是Session,则默认设置cookie退出浏览器 清空 if (ConfigExtensions.Configuration[KeyHelper.LOGINSAVEUSER] == "Session") { await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { AllowRefresh = false }); } else { //根据配置保存浏览器用户信息,小时单位 var hours = int.Parse(ConfigExtensions.Configuration[KeyHelper.LOGINCOOKIEEXPIRES]); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(hours), IsPersistent = true, AllowRefresh = false }); } //获得第一条站点,并保存到session中 var site = await _siteService.GetListAsync(m => !m.IsDel, m => m.AddTime, DbOrderEnum.Asc); //把权限存到缓存里 var menuSaveType = ConfigExtensions.Configuration[KeyHelper.LOGINAUTHORIZE]; if (menuSaveType == "Redis") { RedisHelper.Set(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu); RedisHelper.Set(KeyHelper.NOWSITE, site.data.FirstOrDefault()); } else { MemoryCacheService.Default.SetCache(KeyHelper.NOWSITE, site.data.FirstOrDefault()); MemoryCacheService.Default.SetCache(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu, 600); } token = JwtHelper.IssueJWT(new TokenModel() { Uid = user.Guid, UserName = user.LoginName, Role = "Admin", TokenType = "Web" }); MemoryCacheService.Default.RemoveCache("LOGINKEY"); MemoryCacheService.Default.RemoveCache(KeyHelper.LOGINCOUNT); #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Info", Message = "登录:" + parm.loginname, Callsite = "/fytadmin/login", IP = Utils.GetIp(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (Exception ex) { apiRes.message = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Error", Message = "登录失败!" + ex.Message, Exception = ex.Message, Callsite = "/fytadmin/login", IP = Utils.GetIp(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } apiRes.statusCode = (int)ApiEnum.Status; apiRes.data = token; return(Ok(apiRes)); }
public async Task <ApiResult <string> > Login([FromBody] SysAdminLogin parm) { var apiRes = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; var token = ""; try { #region 1. 从缓存获取公钥私钥解密,再解密密码 //获得公钥私钥,解密 var rsaKey = MemoryCacheHelper.Get <List <string> >(KeyModel.LoginKey); if (rsaKey == null) { apiRes.msg = "登录失败,请刷新浏览器再次登录"; return(apiRes); } //Ras解密密码 var ras = new RSAEncrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); #endregion #region 2. 判断用户登录次数限制以及过期时间 //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(Appsettings.Configuration[KeyModel.LoginCount]); //获得登录次数和过期时间 SysAdminLoginConfig loginConfig = MemoryCacheHelper.Get <SysAdminLoginConfig>(KeyModel.LoginCount) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { apiRes.msg = "您的登录以超过设定次数,请稍后再次登录~"; return(apiRes); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } #endregion #region 3. 从数据库查询该用户 //查询登录结果 var dbres = _adminService.LoginAsync(parm).Result; if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(Appsettings.Configuration[KeyModel.LogindElayMinute]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); apiRes.msg = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(apiRes); } //记录登录次数,保存到session MemoryCacheHelper.Set(KeyModel.LoginCount, loginConfig); //提示用户错误和登录次数信息 apiRes.msg = dbres.msg + " 您还剩余" + (configLoginCount - loginConfig.Count) + "登录次数"; return(apiRes); } #endregion #region 4. 设置Identity User信息 var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, user.ID), new Claim(ClaimTypes.Role, user.RoleId), new Claim(ClaimTypes.Thumbprint, user.HeadPic), new Claim(ClaimTypes.Name, user.RelName), new Claim(ClaimTypes.WindowsAccountName, user.Account), new Claim(ClaimTypes.UserData, user.LastLoginTime.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); if (Appsettings.Configuration[KeyModel.LoginSaveUser] == "Session") {//如果保存用户类型是Session,则默认设置cookie退出浏览器 清空,并且保存用户信息 await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { AllowRefresh = false }); } else { //根据配置保存浏览器用户信息,小时单位 var hours = int.Parse(Appsettings.Configuration[KeyModel.LoginCookieExpires]); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(hours), IsPersistent = true, AllowRefresh = false }); } #endregion #region 5. 保存权限信息到缓存 if (dbres.data.menu != null) { var menuSaveType = Appsettings.Configuration[KeyModel.LoginAuthorize]; if (menuSaveType == "Redis") { RedisCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } else { MemoryCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } } #endregion #region 6. 生成token信息,并且返回给前端 token = JwtHelper.IssueToken(new TokenModel() { UserID = user.ID, UserName = user.RelName, UserAccount = user.Account, Role = "AdminPolicy", ProjectName = "DL.Admin" }); MemoryCacheHelper.Del <string>(KeyModel.LoginKey); MemoryCacheHelper.Del <string>(KeyModel.LoginCount); #endregion #region 7. 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 1, Message = "登录", Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (Exception ex) { apiRes.msg = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 4, Message = "登录失败!" + ex.Message, Exception = ex.Message, Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } apiRes.statusCode = (int)ApiEnum.Status; apiRes.data = token; return(apiRes); }
public async Task <IActionResult> Login([FromBody] SysAdminLogin parm) { var res = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; try { //获得公钥私钥,解密 var rsaKey = await _cache.GetAsync <List <string> >($"LOGINKEY:{parm.lid}"); if (rsaKey == null) { res.message = "登录失败,请刷新浏览器再次登录"; return(Ok(res)); } //Ras解密密码 var ras = new RSACrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(_config[KeyHelper.LOGINCOUNT]); //获得登录次数和过期时间 var loginConfig = await _cache.GetAsync <SysAdminLoginConfig>(KeyHelper.LOGINCOUNT) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { res.message = "您的登录以超过设定次数,请稍后再次登录~"; return(Ok(res)); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } #region 验证码 var captcha = new SimpleCaptcha(); if (!captcha.Validate(parm.code, parm.cid)) { res.message = "验证码错误"; res.statusCode = (int)ApiEnum.ParameterError; return(Ok(res)); } #endregion //查询登录结果 var dbres = await _adminService.LoginAsync(parm); if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(_config[KeyHelper.LOGINDELAYMINUTE]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); res.message = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(Ok(res)); } //记录登录次数,保存到session await _cache.SetAsync(KeyHelper.LOGINCOUNT, loginConfig); //提示用户错误和登录次数信息 res.message = dbres.message; return(Ok(res)); } var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.PrimarySid, user.IsSystem.ToString()), new Claim(ClaimTypes.Sid, user.Guid), new Claim(ClaimTypes.Role, "授权用户"), new Claim(ClaimTypes.Name, user.TrueName), new Claim(ClaimTypes.WindowsAccountName, user.LoginName), new Claim(ClaimTypes.UserData, user.UpLoginDate.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity); ////如果保存用户类型是Session,则默认设置cookie退出浏览器 清空 //if (_config[KeyHelper.LOGINSAVEUSER] == "Session") //{ // await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties // { // AllowRefresh = false // }); //} //else //{ // await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties // { // ExpiresUtc = DateTime.UtcNow.AddHours(_config.GetValue(KeyHelper.LOGINCOOKIEEXPIRES, 0.5D)), // IsPersistent = true, // AllowRefresh = false // }); //} //把权限存到缓存里 await _cache.SetAsync(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu); res.data = JwtHelper.IssueJWT(new TokenModel() { Uid = user.Guid, UserName = user.LoginName, Role = "Admin", TokenType = "Web" }); await _cache.RemoveAsync($"LOGINKEY:{parm.lid}"); await _cache.RemoveAsync(KeyHelper.LOGINCOUNT); #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Info", Message = "登录:" + parm.loginname, Callsite = "/fytadmin/login", IP = HttpContext.GetIP(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (CryptographicException) { res.message = "登录失败,请刷新浏览器重试"; res.statusCode = (int)ApiEnum.Error; return(Ok(res)); } catch (Exception ex) { var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Error", Message = "登录失败!" + ex.Message, Exception = ex.ToString(), Callsite = "/fytadmin/login", IP = HttpContext.GetIP(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); res.message = "登录失败,请刷新浏览器重试"; res.statusCode = (int)ApiEnum.Error; return(Ok(res)); } res.statusCode = (int)ApiEnum.Status; return(Ok(res)); }