2011-02-03 55 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