2011-05-10 194 views
2

我想在我的ASP.NET應用程序中實現Facebook和GMail的功能。保持登錄窗口+表單登錄

我使用窗口和窗體登錄的組合,所有這一切都工作得很好。

我有一個登錄頁面,其中有下面的代碼:

public const int LOGON32_LOGON_INTERACTIVE = 2; 
    public const int LOGON32_PROVIDER_DEFAULT = 0; 

    IntPtr token; 
    IntPtr tokenDuplicate; 

    [DllImport("advapi32.dll", SetLastError = true)] 
    public static extern int LogonUserA(String lpszUserName, 
     String lpszDomain, 
     String lpszPassword, 
     int dwLogonType, 
     int dwLogonProvider, 
     ref IntPtr phToken); 
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    public static extern int DuplicateToken(IntPtr hToken, 
     int impersonationLevel, 
     ref IntPtr hNewToken); 

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    public static extern bool RevertToSelf(); 

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
    public static extern bool CloseHandle(IntPtr handle); 


protected void LoginButton_Click(object sender, EventArgs e) 
     { 
if (LogonUserA(userName, Domain.Text, Password.Text, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) == 0) 
      { 
       BadCredentials.Visible = true; 
       BadCredentials.Text = "Not A Valid User"; 
       Global.logger.Info("LogonUserA failed with GetLastWin32Error code =" + Marshal.GetLastWin32Error()); 
       return; 
      } 
      Global.logger.Info("LogonUserA is sucessful"); 


       if (DuplicateToken(token, 2, ref tokenDuplicate) == 0) 
       { 
        BadCredentials.Visible = true; 
        BadCredentials.Text = "Internal Error: DuplicateToken failed"; 
        return; 
       } 

Session["TokenDuplicate"] = tokenDuplicate; 
      if (new GUIUtility().impersonateValidUser(Session) == false) 
      { 
       BadCredentials.Visible = true; 
       BadCredentials.Text = "Impersonation failed"; 
       return; 
      } 

if (GUIUtility.IsUserPartOfWindowsGroup(compUsrNameForEncryption, adminGroupName) == true) 
      { 
       // The user is Instance Admin 

       BadCredentials.Visible = false; 


      } 
// Create the authentication ticket 
     FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,       // version 
             UserName.Text,   // user name 
             DateTime.Now,    // creation 
             DateTime.Now.AddMinutes(60),// Expiration 
             false,      // Persistent 
             role);   // User data 

     // Now encrypt the ticket. 
     string encryptedTicket = FormsAuthentication.Encrypt(authTicket); 

     // Create a cookie and add the encrypted ticket to the 
     // cookie as data. 
     HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);    

     //authCookie.Secure = FormsAuthentication.RequireSSL; 

     // Add the cookie to the outgoing cookies collection. 
     HttpContext.Current.Response.Cookies.Add(authCookie); 
     //Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false)); 
     Response.Redirect("~/Default.aspx"); 
     // Company Admin has logged on 

} 

這是有關於我的web.config這可能是有用的:

<authentication mode="Forms"> 
     <forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" name="GUI" slidingExpiration="true" timeout="30" path="/"> 
     </forms> 
    </authentication> 
    <authorization> 
     <deny users="?"/> 
     <allow users="*"/> 
    </authorization> 

<sessionState mode="InProc" cookieless="false" timeout="30"/> 

    <!-- 
     The <customErrors> section enables configuration 
     of what to do if/when an unhandled error occurs 
     during the execution of a request. Specifically, 
     it enables developers to configure html error pages 
     to be displayed in place of a error stack trace. 
    --> 
    <customErrors mode="On" defaultRedirect="~/Login.aspx"> 
     <error statusCode="403" redirect="NoAccess.htm" /> 
     <error statusCode="404" redirect="FileNotFound.htm" /> 
    </customErrors> 

這段代碼在我的世界。 ascx:

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 

     try 
     { 
      string cookieName = FormsAuthentication.FormsCookieName.ToString(); 
      HttpCookie authCookie = Context.Request.Cookies[cookieName]; 
      if (null != authCookie) 
      { 
       authCookie.Secure = true; 
      } 
     } 
     catch (Exception ex) 
     { 
      Global.logger.Error("Application_BeginRequest: Exception: " + ex); 
     } 
    } 

    protected void Application_AuthenticateRequest(object sender, EventArgs e) 
    { 
     // Extract the forms authentication cookie 

     string redirectSecureUrl = Request.Url.ToString(); 

     string cookieName = FormsAuthentication.FormsCookieName.ToString(); 
     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) 
     { 
      Global.logger.Error("Application_AuthenticateRequest: Exception: " + ex); 

      return; 
     } 

     if (null == authTicket) 
     { 
      // Cookie failed to decrypt. 
      return; 
     } 

     // When the ticket was created, the UserData property was assigned a 
     // pipe delimited string of role names. 
     string[] roles = authTicket.UserData.Split(new char[] { '|' }); 

     // Create an Identity object 
     FormsIdentity id = new FormsIdentity(authTicket); 

     // This principal will flow throughout the request. 
     GenericPrincipal principal = new GenericPrincipal(id, roles); 
     // Attach the new principal object to the current HttpContext object 
     Context.User = principal; 
    } 

如果我讓持久cookie爲true而不是false,會發生什麼?

謝謝。

+0

...你試過了嗎? – Jason 2011-05-10 20:48:16

+0

我試着改變它爲false仍然沒有行爲改變..當打開登錄頁面並登錄一次,然後打開該瀏覽器的新窗口,並嘗試打開網站,,我不需要再次登錄..但是當我關閉所有的窗戶,然後再次打開應用程序,然後回到登錄屏幕。 – user175084 2011-05-10 21:02:40

+0

因此,我希望它保持登錄狀態,而不要求他再次登錄,除非我按下登出 – user175084 2011-05-10 21:05:35

回答

1

僅供參考...

如果你使用真正的一個cookie具有固定到期日將被創建,而不是僅會話cookie的。 Cookie &因此認證票據將在瀏覽器關閉後存活。

Simon

+0

可以ü給我一個例子或一些參考..它將安靜有幫助 – user175084 2011-05-20 00:47:47

+0

.Net參考創建一個持久的cookie - > http://msdn.microsoft.com/en-us/library/ka5ffkce(v=VS 0.90)的.aspx – 2011-06-28 10:10:46