2008-09-03 94 views
8

我们在ASP.NET中有一个自定义MembershipProvider。现在有2种可能情景的用户可以验证:在ASP.NET中使用不带登录控件的自定义MembershipProvider

  1. 用户通过登录页面login.aspx通过输入自己的用户名/密码。我已使用登录控制并将其与MyMembershipProvider关联。这工作得很好。

  2. 身份验证令牌通过查询字符串中的某个URL传递,形成不同的网站。为此,我在MembershipProvider.Validate(string authenticationToken)中有一个过载,这实际上验证了用户。在这种情况下,我们不能使用登录控件。现在我怎样才能使用相同的MembershipProvider来验证用户而不实际使用登录控制?我试图手动调用Validate,但这不是登录用户。

这里是我使用

if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) { 
    string ticket = Request.QueryString["authenticationToken"]; 
    MyMembershipProvider provider = Membership.Provider as MyMembershipProvider; 
    if (provider != null) { 
     if (provider.ValidateUser(ticket)) 
      // Login Success 
     else 
      // Login Fail 
    } 
} 

回答

13

验证成功后的代码片段,您需要在用户登录通过调用FormsAuthentication.Authenticate:http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx

编辑:这是FormsAuthentication.SetAuthCookie: http://msdn.microsoft.com/en-us/library/twk5762b.aspx

此外,为了将用户重定向回他想去,请拨打:FormsAuthentication.RedirectFromLoginPage:http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx

link text

4

你可以设置自己的FormsAuthenticationTicket如果验证成功。

就是这样;

if (provider != null) { 
    if (provider.ValidateUser(ticket)) { 
     // Login Success 
     FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
      1, //version 
      someUserName, //name 
      DateTime.Now, //issue date 
      DateTime.Now.AddMinutes(lengthOfSession), //expiration 
      false, // persistence of login 
      FormsAuthentication.FormsCookiePath 
     ); 

     //encrypt the ticket 
     string hash = FormsAuthentication.Encrypt(authTicket); 
     HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); 

     Response.Cookies.Add(cookie); 
     Response.Redirect(url where you want the user to land); 
    } else { 
     // Login Fail 
    } 
} 
+0

我一直在试图知道如何认证实际工作。谢谢。它帮了我很多 – Krishh 2012-07-17 03:13:12

1

对于将身份验证信息直接存储为cookie的情况,您是正确的。但是使用强大的散列函数(例如MD5 + SHA1)非常安全。 顺便说一句,如果你使用会话(这也只是一个哈希cookie),你可以将auth信息附加到它。

相关问题