2011-02-03 56 views
0

LoginPage.aspx: -自定義驗證模塊繼承IHttpModule的問題

protected void Button1_Click(object sender, EventArgs e) 
      { 
       Context.Items["Username"] = txtUserId.Text; 
       Context.Items["Password"] = txtPassword.Text; 
       // 
       FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Context.Items["Username"].ToString(), DateTime.Now, DateTime.Now.AddMinutes(10), true, "users", FormsAuthentication.FormsCookiePath); 

       // Encrypt the cookie using the machine key for secure transport 
       string hash = FormsAuthentication.Encrypt(ticket); 
       HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName, // Name of auth cookie 
        hash); // Hashed ticket 

       // Set the cookie's expiration time to the tickets expiration time 
       if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; 
       Response.Cookies.Add(cookie); 
       Response.Redirect("Default.aspx"); 
      } 

Global.asax文件: -

void Application_AuthenticateRequest(object sender, EventArgs e) 
     { 
      if (HttpContext.Current.User != null) 
      { 
       if (HttpContext.Current.User.Identity.IsAuthenticated) 
       { 
        if (HttpContext.Current.User.Identity is FormsIdentity) 
        { 
         FormsIdentity id = 
          (FormsIdentity)HttpContext.Current.User.Identity; 
         FormsAuthenticationTicket ticket = id.Ticket; 
         // Get the stored user-data, in this case, our roles 
         string userData = ticket.UserData; 
         string[] roles = userData.Split(','); 
         HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles); 
         Response.Write(HttpContext.Current.User.Identity.Name); 
         Response.Redirect("Default.aspx"); 
        } 
       } 
      } 
     } 

我收到以下錯誤

This webpage has a redirect loop. 

The webpage at http://localhost:1067/Default.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer. 
+0

爲什麼我得到重定向錯誤? – 2011-02-04 07:22:15

+0

`Application_AuthenticateRequest`在每個*請求*上觸發,因此當您登錄時,您會按預期發送到Default.aspx。但是,在該頁面呈現之前,將調用此代碼並將瀏覽器重定向到Default.aspx。但是在渲染這段代碼之前,它再一次將瀏覽器重定向到Default.aspx。重複這個過程,直到檢測到(如果你幸運的話)無限重定向。 – 2011-02-04 20:49:36

+0

另外,請不要更改您的整個帖子。您可以通過修改來修改它,但是您已經從IHttpModule切換到使用global.asax事件,這些事件是分開的。如果你走向不同的方向,請創建一個新問題,並參考舊的相關內容。 – 2011-02-04 20:52:14

回答

2

這是你模塊應該看起來像什麼的粗略想法。您的模塊將在上運行,每請求。您不會調用它或將任何內容傳遞給它,它只會在ASP.Net設置爲處理請求時自動觸發。

你的模塊將做兩兩件事,1)在登錄頁面驗證用戶,2)驗證後續頁面上的用戶。第一步是訂閱BeginRequest方法,該方法將以當前的HttpApplication作爲第一個參數。從那裏你需要確定用戶是否在你的登錄頁面上。如果他們不在您的登錄頁面上,請檢查您的會話或cookie或querystring標記,或者您正在使用的任何內容以確保它們仍然有效。如果它們無效,則將它們反彈回登錄頁面。

如果它們在您的登錄頁面已經發布了POST,請查看原始表單字段並驗證它們。文本框,複選框等在這裏不存在,只有原始的表單域。如果它們有效,請設置您的身份驗證令牌(會話,cookie等)。如果它們無效,請重定向到登錄頁面或注入「重試」消息或其他內容。

此外,如果您雙擊後留言請reference it,使我們可以效仿一下已經說的鏈條。

class MyModule : IHttpModule 
{ 

    void IHttpModule.Init(HttpApplication context) 
    { 
     //Subscribe to the BeginRequest event 
     context.BeginRequest += new EventHandler(this.Application_BeginRequest); 
    } 
    private void Application_BeginRequest(Object source, EventArgs e) 
    { 
     //Initialize our variables, null checks should be put here, too 
     HttpApplication app = (HttpApplication)source; 
     HttpContext context = app.Context; 
     System.Web.SessionState.HttpSessionState s = context.Session; 

     //Normally our module needs to validate every request to make sure our request is still authenticated. 
     //The exception to that rule is on our logon page where they obviously don't have credentials yet. 
     if(!context.Request.FilePath.ToLowerInvariant().StartsWith("/login.aspx")){ 
      //If we're here then we're not on the logon page, validate our current session according to whatever logic we want 
      if (s != null && s["isvalid"] == "true"){ 
       return; 
      }else{ 
       context.Response.Redirect("/login.aspx"); 
      } 
     }else{ 
      //If we're here then we're on the login page itself. If there's a post, assume that they've hit the login button 
      if (context.Request.HttpMethod == "POST") 
      { 
       //Whatever your form variables are called 
       string username = context.Request.Form["username"]; 
       string password = context.Request.Form["password"]; 
       //Your own validation logic would go here 
       if (MyCustomLogin.IsUserValid(username, password)) 
       { 
        s["isvalid"] = "true"; 
        context.Response.Redirect("/Home.aspx");  
       }else{ 
        s["isvalid"] = "false"; 
        context.Response.Redirect("/login.aspx?error=invalid_login"); 
       } 
      }else{ 
       //If we're here then the request is probably a GET or HEAD which would be from a person 
       //initially browsing to our page so just do nothing and pass it through normally 
      } 
     } 
    } 
} 
0

有簽約後沒有直接的方式來訪問模塊中的這些信息(對於經過身份驗證的用戶,您可以通過上下文訪問用戶名,但是而不是密碼)。該模塊檢查請求是否攜帶了所需的認證信息,並根據該請求提供或拒絕該請求。除非您故意從登錄頁面收集此信息並將其存儲在可以在模塊中訪問它的地方,例如會話。但理想情況下,存儲密碼不被廣泛推薦,收集它用於驗證和銷燬。

你可能會非常扔在你爲什麼要訪問的模塊和球員在這個信息然後可以建議的方法來完成它的原因更多的光。

編輯,CHANDAN後評論:

@Chandan,在這裏您的評論建議我,你想要做的是使用HTTP模塊進行身份驗證作爲對使用標準形式的認證。如果我在軌道上,那麼你可以在代碼項目http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx上檢查這個項目。 Goodluck