2014-01-23 4 views
1

Используя FormsAuthentication, я создаю FormsAuthenticationTicket, шифруя, добавляя это в файл cookie с помощью Response.Cookies.Add (authCookie). Затем я делаю перенаправление с помощью Response.Redirect на исходную страницу, которая была запрошена. Существует код в Global.asax в методе Application_AuthenticateRequest, который пытается получить файл cookie - HttpCookie authCookie = Context.Request.Cookies [cookieName]. По какой-то причине, однако, когда он попадает в код Global.asax после вызова перенаправления, в коллекции нет файлов cookie. На данный момент я немного зациклен на том, почему он теряет куки из коллекции. Любые мысли о том, почему это произойдет? Прямо сейчас, я просто работаю в локальном хосте.Не удается получить файл 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; 
}` 
+0

Можете ли вы показать код? – Jason

+0

Вы перенаправляетесь на URL-адрес, принадлежащий другому домену, и устанавливаете файл cookie домена. – Saravanan

+0

Редирект - это просто исходная страница. В этом случае это был Default.aspx. В адресной строке, когда она перенаправляется на страницу входа, она показывает: http: // localhost: 64432/Login? ReturnUrl =% 2fDefault.aspx –

ответ

1

Я был в состоянии решить мою проблему путем корректировки данных, сохранявшихся в USERDATA из FormsAuthenticationTicket. Кажется, что количество данных, которые я пытался вставить, превышало максимум. Как только я удалю, все работает так, как ожидалось.

Смежные вопросы