使用FormsAuthentication,我創建一個FormsAuthenticationTicket,進行加密,並使用Response.Cookies.Add(authCookie)將其添加到cookie中。然後我使用Response.Redirect重定向到請求的原始頁面。在Application_AuthenticateRequest方法中的Global.asax中有代碼檢索cookie - HttpCookie authCookie = Context.Request.Cookies [cookieName]。但是,出於某種原因,當重定向被調用後它碰到Global.asax代碼時,集合中就沒有cookie了。在這一點上,我有點難以理解它爲什麼會丟失集合中的cookie。任何想法爲什麼會發生?現在,我只是在localhost內部工作。無法檢索cookie
登錄頁面代碼:
string adPath = "LDAP://ldapserveraddress";
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if (true == adAuth.IsAuthenticated("ES", txtUsername.Text, txtPassword.Text))
{
string groups = adAuth.GetGroups();
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if (true == isCookiePersistent)
authCookie.Expires = authTicket.Expiration;
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
string redirect = FormsAuthentication.GetRedirectUrl(txtUsername.Text, false);
//You can redirect now.
Response.Redirect(redirect,false);
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch (Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
的Global.asax代碼(Application_AuthenticateRequest):
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
//There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
//Write the exception to the Event Log.
return;
}
if (null == authTicket)
{
//Cookie failed to decrypt.
return;
}
//When the ticket was created, the UserData property was assigned a
//pipe-delimited string of group names.
string[] groups = authTicket.UserData.Split(new char[] { '|' });
//Create an Identity.
GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");
//This principal flows throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, groups);
Context.User = principal;
}`
你能顯示一些代碼嗎? – Jason
您是否重定向到屬於不同域的url並設置域cookie。 – Saravanan
重定向僅僅是最初請求的頁面。在這種情況下,它是Default.aspx。在地址欄中,當它重定向到登錄頁面時,它顯示:http:// localhost:64432/Login?ReturnUrl =%2fDefault.aspx –