protected void Page_Load(object sender, System.EventArgs e) { string queryString = WebUtils.GetQueryString("lang"); if (Language.Contain(queryString)) { CookieUtils.SetCookie("langcookie", queryString, 2592000); string queryString2 = WebUtils.GetQueryString("jumpurl"); if (!string.IsNullOrEmpty(queryString2)) { base.Response.Redirect(queryString2); } else if (base.Request.UrlReferrer != null) { base.Response.Redirect(base.Request.UrlReferrer.ToString()); } else { base.Response.Redirect("/"); } } else { base.Response.Write(WebUtils.GetCaption("CMS_NotExistLanguageSet")); base.Response.End(); } }
static async Task <bool> connectAsync(string uri, CancellationToken token, Action <WebSocketWrapper> onConnection, Action <ClientWebSocketOptions> setOptions = null) { ClientWebSocket webSocket = null; var isClosedSuccessfully = true; try { webSocket = new ClientWebSocket(); setOptions?.Invoke(webSocket.Options); await webSocket.ConnectAsync(new Uri(uri), token); } catch (Exception) { webSocket?.Dispose(); throw; } var connection = new WebSocketWrapper(webSocket, CookieUtils.GetCookies(webSocket.Options.Cookies?.GetCookies(new Uri(uri)))); try { onConnection(connection); await connection.ListenReceiveAsync(token); } finally { isClosedSuccessfully = webSocket.State != WebSocketState.Aborted; webSocket?.Dispose(); } return(isClosedSuccessfully); }
public ActionResult SumbitLogon(VOUser user) { if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password)) { return(RedirectToAction("Logon", "LogonForm", new { message = "登录名,密码不能为空!" })); } JsonUser jsonUser = UserService.CheckUserPassword(user.UserName, user.Password); CookieUtils.AddCookie("LogonID", user.UserName, System.Web.HttpContext.Current); if (user.RememberMe) { HttpCookie cookie = CookieUtils.GetCookie(System.Web.HttpContext.Current, "LogonID"); cookie.Expires = DateTime.Now.AddDays(7); } GlobalVariables.CurrentUser = jsonUser; if (jsonUser == null) { return(RedirectToAction("Logon", "LogonForm", new { message = "用户名,密码验证失败!" })); } return(RedirectToAction("Index", "ParticipateConsultation")); }
public async Task <ActionResult> Login(LoginModel model) { if (!ModelState.IsValid) { return(View(model)); } if (!VeryfyCodeUtility.IsVerifyCodeMatch(Session, model.ValidateCode)) { ModelState.AddModelError("ValidateCode", "验证码错误!"); return(View(model)); } var loginResult = await UsersRepository.Login(model.UserName, model.Password); if (loginResult.Status == SigninStatus.Succ) { FormsAuthSvc.CreateAuthenticationTicket(loginResult.UserInfo, Response, HttpContext, model.IsRemember); //添加到Fom if (model.IsRemember) { CookieUtils.SetCookie(FormsAuthSvc.GetUserNameCookieKey(), model.UserName, true); } else { CookieUtils.RemoveCookie(FormsAuthSvc.GetUserNameCookieKey()); } //添加登录日志 await SysOperationLogRepository.Insert(TableSource.Users, OperationType.UserLogin, "", ""); return(Redirect(Url.AdminHome())); } ModelState.AddModelError("UserName", "登录失败!" + loginResult.Status.GetDescriotion()); return(View(model)); }
/// <summary>获取TGC /// </summary> public AccountInfo GetTicketGranting() { var cookieString = CookieUtils.Get("TGC"); var account = string.IsNullOrEmpty(cookieString) ? null : DecodeCookie(cookieString); return(account); }
public string UserLogin(string userName, bool isAutoLogin) { if (string.IsNullOrEmpty(userName)) { return(null); } var userInfo = UserManager.GetUserInfoByUserName(userName); if (userInfo == null || userInfo.IsLockedOut || !userInfo.IsChecked) { return(null); } UserInfo = userInfo; var expiresAt = DateTime.Now.AddDays(AccessTokenExpireDays); var accessToken = GetAccessToken(UserId, UserName, expiresAt); DataProvider.UserDao.UpdateLastActivityDateAndCountOfLogin(UserInfo); LogUtils.AddUserLoginLog(userName); if (isAutoLogin) { CookieUtils.SetCookie(AuthKeyUserCookie, accessToken, expiresAt); } else { CookieUtils.SetCookie(AuthKeyUserCookie, accessToken); } return(accessToken); }
public string AdminLogin(string userName, bool isAutoLogin) { if (string.IsNullOrEmpty(userName)) { return(null); } var adminInfo = AdminManager.GetAdminInfoByUserName(userName); if (adminInfo == null || adminInfo.IsLockedOut) { return(null); } AdminInfo = adminInfo; IsAdminLoggin = true; var expiresAt = DateTime.Now.AddDays(AccessTokenExpireDays); var accessToken = GetAccessToken(adminInfo.Id, adminInfo.UserName, expiresAt); LogUtils.AddAdminLog(adminInfo.UserName, "管理员登录"); if (isAutoLogin) { CookieUtils.SetCookie(AuthKeyAdminCookie, accessToken, expiresAt); } else { CookieUtils.SetCookie(AuthKeyAdminCookie, accessToken); } return(accessToken); }
public ActionResult Logout() { CookieUtils.RemoveCookie("LogonID", System.Web.HttpContext.Current); GlobalVariables.CurrentUser = new JsonUser(); return(RedirectToAction("Logon", "LogonForm", new { message = "您已成功注销!" })); }
public IHttpActionResult Check(string name, [FromBody] CaptchaInfo captchaInfo) { try { var code = CookieUtils.GetCookie("SS-" + name); if (string.IsNullOrEmpty(code) || CacheUtils.Exists($"SiteServer.API.Controllers.V1.CaptchaController.{code}")) { return(BadRequest("验证码已超时,请点击刷新验证码!")); } CookieUtils.Erase("SS-" + name); CacheUtils.InsertMinutes($"SiteServer.API.Controllers.V1.CaptchaController.{code}", true, 10); if (!StringUtils.EqualsIgnoreCase(code, captchaInfo.Captcha)) { return(BadRequest("验证码不正确,请重新输入!")); } return(Ok(new { Value = true })); } catch (Exception ex) { LogUtils.AddErrorLog(ex); return(InternalServerError(ex)); } }
/// <summary> /// Gets Target cookies /// </summary> /// <returns>Target cookies</returns> public Dictionary <string, TargetCookie> GetCookies() { var cookies = new Dictionary <string, TargetCookie>(); if (this.Response == null || this.Response.Status < (int)HttpStatusCode.OK || this.Response.Status >= (int)HttpStatusCode.Ambiguous) { return(cookies); } var targetCookie = CookieUtils.CreateTargetCookie(this.Request.SessionId, this.Response.Id.TntId); if (targetCookie != null) { cookies.Add(TargetConstants.MboxCookieName, targetCookie); } var clusterCookie = CookieUtils.CreateClusterCookie(this.Response.Id.TntId); if (clusterCookie != null) { cookies.Add(TargetConstants.ClusterCookieName, clusterCookie); } return(cookies); }
private void SetTokenCookies(String accessToken, SecurityToken token, String refreshToken) { //There is no end to the pain of trying to get this right, fix the path here to ensure its correct. var cookiePath = CookieUtils.FixPath(Options.CookiePath); var expires = Options.StoreCookiesInSession ? default(DateTimeOffset?) : token.ValidTo; cookieManager.AppendResponseCookie(Context, BearerCookieName, accessToken, new CookieOptions() { Secure = true, HttpOnly = Options.BearerHttpOnly, Path = cookiePath, Expires = expires, SameSite = Options.SameSite }); cookieManager.AppendResponseCookie(Context, RefreshCookieName, refreshToken, new CookieOptions() { Secure = true, HttpOnly = Options.RefreshHttpOnly, Path = cookiePath, Expires = expires, SameSite = Options.SameSite }); }
public string AdminLogin(string userName, bool isAutoLogin) { if (string.IsNullOrEmpty(userName)) { return(null); } var adminInfo = AdminManager.GetAdminInfoByUserName(userName); if (adminInfo == null || adminInfo.Locked) { return(null); } AdminInfo = adminInfo; IsAdminLoggin = true; var expiresAt = TimeSpan.FromDays(Constants.AccessTokenExpireDays); var accessToken = AdminApi.Instance.GetAccessToken(adminInfo.Id, adminInfo.UserName, expiresAt); LogUtils.AddAdminLog(adminInfo, "管理员登录"); if (isAutoLogin) { CookieUtils.SetCookie(Constants.AuthKeyAdminCookie, accessToken, expiresAt); } else { CookieUtils.SetCookie(Constants.AuthKeyAdminCookie, accessToken); } return(accessToken); }
/// <summary> /// 权限控制 /// </summary> private void CheckPermission() { if (string.IsNullOrEmpty(CookieUtils.GetCookieValue("OpenId"))) { Response.Redirect("/login.htm"); } }
public IHttpActionResult Check([FromBody] CheckRequest request) { try { var code = CookieUtils.GetCookie(CookieName); if (string.IsNullOrEmpty(code) || CacheUtils.Exists($"{CookieName}.{code}")) { return(BadRequest("验证码已超时,请点击刷新验证码!")); } CookieUtils.Erase(CookieName); CacheUtils.InsertMinutes($"{CookieName}.{code}", true, 10); if (!StringUtils.EqualsIgnoreCase(code, request.Captcha)) { return(BadRequest("验证码不正确,请重新输入!")); } return(Ok(new { Value = true })); } catch (Exception ex) { return(InternalServerError(ex)); } }
public void Get(string name) { var response = HttpContext.Current.Response; var code = VcManager.CreateValidateCode(); if (CacheUtils.Exists($"SiteServer.API.Controllers.V1.CaptchaController.{code}")) { code = VcManager.CreateValidateCode(); } CookieUtils.SetCookie("SS-" + name, code, DateTime.Now.AddMinutes(10)); response.BufferOutput = true; //特别注意 response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1)); //特别注意 response.Cache.SetCacheability(HttpCacheability.NoCache); //特别注意 response.AppendHeader("Pragma", "No-Cache"); //特别注意 response.ContentType = "image/png"; var validateimage = new Bitmap(130, 53, PixelFormat.Format32bppRgb); var r = new Random(); var colors = Colors[r.Next(0, 5)]; var g = Graphics.FromImage(validateimage); g.FillRectangle(new SolidBrush(Color.FromArgb(240, 243, 248)), 0, 0, 200, 200); //矩形框 g.DrawString(code, new Font(FontFamily.GenericSerif, 28, FontStyle.Bold | FontStyle.Italic), new SolidBrush(colors), new PointF(14, 3)); //字体/颜色 var random = new Random(); for (var i = 0; i < 25; i++) { var x1 = random.Next(validateimage.Width); var x2 = random.Next(validateimage.Width); var y1 = random.Next(validateimage.Height); var y2 = random.Next(validateimage.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } for (var i = 0; i < 100; i++) { var x = random.Next(validateimage.Width); var y = random.Next(validateimage.Height); validateimage.SetPixel(x, y, Color.FromArgb(random.Next())); } g.Save(); var ms = new MemoryStream(); validateimage.Save(ms, ImageFormat.Png); response.ClearContent(); response.BinaryWrite(ms.ToArray()); response.End(); }
/// <summary>生成TGC并写入cookie /// </summary> public void SetTicketGranting(AccountInfo account) { var cookieString = EncodeCookie(account); var exp = _setting.TgcExpiredSeconds == 0 ? DateTime.MaxValue : DateTime.Now.AddSeconds(_setting.TgcExpiredSeconds); CookieUtils.WriteCookie("TGC", cookieString, exp); }
protected void AuthAdministrator() { if (!string.IsNullOrEmpty(CookieUtils.GetCookie(AdministratorAuthCookie))) { var administratorTokenStr = CookieUtils.GetCookie(AdministratorAuthCookie); AdminName = string.IsNullOrEmpty(administratorTokenStr) ? AdminManager.AnonymousUserName : GetAdministratorToken(administratorTokenStr).AdministratorName; } AdminPermissions = PermissionManager.GetInstance(AdminName); }
public ActionResult PutAccount() { var encryptAccount = RequestUtils.GetString("Account"); var callBackUrl = RequestUtils.GetString("CallBackUrl"); var key = RequestUtils.GetString("key"); var account = EncryptUtils.DecryptAccount(encryptAccount, key); CookieUtils.WriteCookie("Account", account.Code, null); return(Redirect(callBackUrl)); }
private void RestoreSession() { Log.Debug("Restoring session"); Client.CookieContainer = CookieUtils.ReadCookiesFromDisk(_cookiPath); AuthData = AuthenticationDataResponse.NewInstance(_dataPath); IsAuthenticated = AuthData is not null; Client.Authenticator = GetAuthenticator(AuthData); }
public JsonResult TryLogOut() { var id = HttpContext.LoginId(); if (id > 0) { LoginMiddleware.LogOutUser(id); } CookieUtils.Set(HttpContext, "login", null); return(new JsonResult(new { isLoggedOut = true })); }
public IActionResult Index() { /* * net core不自带httpcontext 需要在 Startup 注入 * 1、在ConfigureServices 中 services.AddStaticHttpContext(); * 2、在Configure 中 app.UseStaticHttpContext(); */ var builder = new StringBuilder("测试如下:\r\n"); //Post builder.Append($"Post值:{WebUtils.GetFormVal<string>("a")}\r\n"); //IP builder.Append($"IP:{IPUtils.GetIP()}\r\n"); //WebUtils builder.Append($"pid:{WebUtils.GetQueryVal<int>("pid")}\r\n"); //?pid=1 builder.Append($"date:{WebUtils.GetQueryVal<DateTime>("date", new DateTime(1900, 1, 1))}\r\n"); //?date=2020-12-31 //全url builder.Append($"全URL:{WebUtils.GetAbsoluteUri()}\r\n"); //CacheUtils 缓存 DateTime dateTime = DateTime.Now; var cache = new CacheUtils(); var cacheDT = DateTime.Now; if (cache.ContainKey("time")) { cacheDT = cache.Get <DateTime>("time"); } else { cache.Insert <DateTime>("time", dateTime, 3600); } builder.Append($"当前时间:{dateTime.ToFormatString()} \r\n"); builder.Append($"缓存时间:{cacheDT.ToFormatString()} \r\n"); //当前网站目录 builder.Append($"当前网站目录:{SystemUtils.GetMapPath()} \r\n"); builder.Append($"upload目录:{SystemUtils.GetMapPath("/upload")} \r\n"); //cookie CookieUtils.SetCookie("username", "jsonlee"); builder.Append($"username cookie: {CookieUtils.GetCookie("username")} \r\n"); //session SessionUtils.SetSession("username", System.Web.HttpUtility.UrlEncode("刘备")); builder.Append($"username session: {System.Web.HttpUtility.UrlDecode(SessionUtils.GetSession("username"))} \r\n"); return(Content(builder.ToString())); }
public void LogOut(IJRUser user) { var cookieName = GetCookieName(); CookieUtils.RemoveCookie(cookieName); if (user != null) { Cache.Remove(user.UserInfo.GId); } FormsAuthentication.SignOut(); }
private void UpdateStickyLocationHint(DeliveryResponse deliveryResponse) { var tntId = deliveryResponse?.Id?.TntId; if (tntId != null && deliveryResponse.Status >= (int)HttpStatusCode.OK && deliveryResponse.Status < (int)HttpStatusCode.Ambiguous) { Interlocked.Exchange(ref this.stickyLocationHint, CookieUtils.LocationHintFromTntId(tntId)); } }
public ActionResult Login(LoginModel model) { var result = new JsonModel(); #region check params if (model == null) { result.msg = "请输入数据!"; return(Json(result)); } if (string.IsNullOrEmpty(model.UserName)) { result.msg = "请输入用户名"; return(Json(result)); } if (string.IsNullOrEmpty(model.Password) || model.Password.Length < 6) { result.msg = "请输入正确的密码"; return(Json(result)); } if (string.IsNullOrEmpty(model.ValidateCode)) { result.msg = "请输入验证码"; return(Json(result)); } #endregion if (!VeryfyCodeUtility.IsVerifyCodeMatch(Session, model.ValidateCode)) { result.msg = "验证码错误!"; return(Json(result)); } var loginResult = UsersRepository.AdminLogin(model.UserName, model.Password); if (loginResult.Status == SigninStatus.Succ) { FormsAuthSvc.CreateAuthenticationTicket(loginResult.UserInfo, Response, HttpContext, model.IsRemember); //添加到Fom if (model.IsRemember) { CookieUtils.SetCookie(FormsAuthSvc.GetUserNameCookieKey(), model.UserName, true); } else { CookieUtils.RemoveCookie(FormsAuthSvc.GetUserNameCookieKey()); } //添加登录日志 SysOperationLogRepository.Insert(TableSource.Users, OperationType.UserLogin, loginResult.UserInfo.Id); result.code = JsonModelCode.Succ; return(Json(result)); } result.msg = "登录失败!" + loginResult.Status.GetDescriotion(); return(Json(result)); }
public void UserLogin(string userName) { if (string.IsNullOrEmpty(userName)) { return; } UserName = userName; LogUtils.AddUserLoginLog(userName); CookieUtils.SetCookie(UserAccessToken, GetUserTokenByUserName(userName), DateTime.Now.AddDays(AccessTokenExpireDays)); }
public void AdminLogin(string administratorName) { if (string.IsNullOrEmpty(administratorName)) { return; } AdminName = administratorName; LogUtils.AddAdminLog(administratorName, "管理员登录"); CookieUtils.SetCookie(AdministratorAccessToken, GetAdminTokenByAdminName(administratorName), DateTime.Now.AddDays(AccessTokenExpireDays)); }
void Application_BeginRequest(object sender, EventArgs e) { //throw new HttpException(503, "Service unavailable"); if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.QueryString != null) { string rf = HttpContext.Current.Request.QueryString["rf"]; if (!string.IsNullOrEmpty(rf)) { CookieUtils.WriteCookie("rf", rf); } } }
public static string GetCookieWXOpenID(string wxOpenID) { if (CookieUtils.IsExists(COOKIE_WXOPENID_NAME)) { return(CookieUtils.GetCookie(COOKIE_WXOPENID_NAME)); } else { CookieUtils.SetCookie(COOKIE_WXOPENID_NAME, wxOpenID, DateTime.MaxValue); return(wxOpenID); } }
public bool IsCodeValid(string validateCode) { var code = CookieUtils.GetCookie(_cookieName); var isValid = StringUtils.EqualsIgnoreCase(code, validateCode); if (isValid) { CacheUtils.Remove(_cookieName); } return(isValid); }
public void LogOut(IPrincipal user) { var cookieName = GetCookieName(); CookieUtils.RemoveCookie(cookieName); var sysUser = user as ISysUser; if (user != null) { UserRep.RemoveUserCache(sysUser.UserModel.GId); } FormsAuthentication.SignOut(); }