![](/img/trans.png)
[英]OWIN Authentication Cookie information and forcing login even when not expired
[英]Set Form Authentication Cookies Expired Time
我通讀了以下答案 ,我認為應該可以使用,但是在此注釋中的哪部分?
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, isPersistent);
if (!isPersistent)
{
//this is because if it was not set then it got
//automatically set to expire next year even if
//the cookie was not set as persistent
authCookie.Expires = DateTime.Now.AddMinutes(15);
}
Response.Cookies.Add(authCookie);
是在global.asax還是Controller本身中?
以下是我的代碼。
從控制器視圖:
[HttpPost]
public ActionResult Login(User user, string returnUrl)
{
if (ModelState.IsValid)
{
var username = user.Username;
var getPassword = (from item in db.User
where item.Username == username
select new UserModel()
{
Password = item.Password
}
).SingleOrDefault();
if (getPassword != null)
{
var hashingPass = Models.PasswordHash.ValidatePassword(user.Password, getPassword.Password);
var getAdmin = (from item in db.User
where item.Username == username && hashingPass == true
select new UserModel()
{
UserId = item.UserId
}
).ToList();
if (getAdmin.Count.Equals(1))
{
FormsAuthentication.SetAuthCookie(username, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index");
}
}
else
{
ModelState.AddModelError("", "The username or password provided is incorrect.");
}
}
else
{
ModelState.AddModelError("", "The username or password provided is incorrect.");
}
}
return View(user);
}
從HTML視圖:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<form role="form">
<fieldset>
<div class="form-group">
<label for="Username">Username</label>
<input class="form-control" placeholder="Enter Username" name="Username" id="Username" type="text" autofocus oninput="setCustomValidity('')" required/>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input class="form-control" placeholder="Enter Password" name="Password" id="Password" type="password" value="" oninput="setCustomValidity('')" required>
</div>
<button type="submit" style="background-color:#f7aa52; border:1px solid #f78952; color:#fff;" class="btn btn-lg btn-block">Login</button>
</fieldset>
</form>
}
它在控制器級別。
您也可以在web.config下的cookie到期下指定
<system.web>
<authentication mode="Forms">
<forms timeout="50000000" slidingExpiration="true"/>
</authentication>
</system.web>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.