下面的代碼將創建一個cookie來保持用戶登錄。
// login etc
if (chkRemember.Checked)
{
// calculate the total number of minutes in 20 days to use as the time out.
int timeout = (int)TimeSpan.FromDays(30).TotalMinutes;
// create an authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(txtUserName.Text, true, timeout);
// Encrypt the ticket
string encrptedTicked = FormsAuthentication.Encrypt(ticket);
// create the cookie for the ticket, and put the ticket inside
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrptedTicked);
// give cookie and ticket same expiration
cookie.Expires = ticket.Expiration;
// Attach cookie to current response. it will now to the client and then back to the webserver with every request
HttpContext.Current.Response.Cookies.Set(cookie);
// send the user to the originally requested page.
string requestedPage = FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);
Response.Redirect(requestedPage, true);
}
else
{
// login without saving cookie to client
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
}
能否請您闡述一下你想達到什麼樣的?用戶使用哪種身份驗證方法進行身份驗證,以及與其他方法相關的方式如何?您是否希望用戶通過表單進行身份驗證,然後才能使用基於令牌的webAPI? (另外,自動重新登錄的cookie如何工作?這聽起來像是一個漏洞,但顯然我不知道細節。) –
請參閱https://stackoverflow.com/questions/549/the-definitive-guide-以外形爲主的網站的身份驗證?RQ = 1 – s3raph86