/// <summary> /// 创建Session /// </summary> /// <param name="currentSession"></param> internal void Create(UserAuthSession currentSession) { using (var stream = new StreamWriter(_filePath, true, Encoding.UTF8)) { stream.WriteLine(currentSession.ToString()); } }
public async Task<ActionResult> Index(PassportLoginRequest model) { if (ModelState.IsValid == false) { //实体验证失败 return View(model); } var user = await UserManager.FindAsync(model.UserName, model.Password); if (user == null) { ModelState.AddModelError("", "Invalid username or password."); return View(model); } //获取当前未到期的Session var currentSession = _authSessionService.GetValidAuthSession(model.AppKey, user.UserName); if (currentSession == null) { currentSession = new UserAuthSession { AppKey = model.AppKey, CreateTime = DateTime.Now, InvalidTime = DateTime.Now.AddYears(1), IpAddress = Request.UserHostAddress, SessionKey = Guid.NewGuid().ToString().ToMd5(), UserName = user.UserName }; _authSessionService.Create(currentSession); } else { _authSessionService.RefreshSession(currentSession); } var redirectUrl = string.Format("{0}?SessionKey={1}&SessionUserName={2}", "http://test.com", currentSession.SessionKey, user.UserName); //跳转默认回调页面 return Redirect(redirectUrl); }
public static UserAuthSession FromString(string strUser) { if (string.IsNullOrWhiteSpace(strUser)) { throw new ArgumentNullException("user"); } var arr = strUser.Split(','); if (arr.Length != 6) { throw new InvalidOperationException("user is not valid"); } var user = new UserAuthSession(); user.SessionKey = arr[0]; user.AppKey = arr[1]; user.UserName = arr[2]; user.IpAddress = arr[3]; user.InvalidTime = DateTime.Parse(arr[4]); user.CreateTime = DateTime.Parse(arr[5]); return user; }
/// <summary> /// 延长有效期 /// </summary> /// <param name="session"></param> internal void RefreshSession(UserAuthSession session) { string content; var s = session.ToString(); session.InvalidTime=DateTime.Now.AddHours(2); using (var read = new StreamReader(_filePath)) { content = read.ReadToEnd().Replace(s, session.ToString()); } using (var stream = new StreamWriter(_filePath, true, Encoding.UTF8)) { stream.WriteLine(content); } }