在ASP.NET中使用没有登录控件的自定义MembershipProvider

时间:2020-03-05 18:47:01  来源:igfitidea点击:

我们在ASP.NET中有一个自定义的MembershipProvider。现在可以验证用户的两种可能情况:

  • 用户通过输入" login.aspx"页面的用户名/密码登录。我已经使用了登录控件并将其与" MyMembershipProvider"链接。这工作得很好。
  • 身份验证令牌通过查询字符串中的某个URL从不同的网站传递。为此,我在MembershipProvider.Validate(string authenticationToken)中有一个重载,它实际上是在验证用户。在这种情况下,我们不能使用登录控件。现在如何在不实际使用登录控件的情况下使用相同的MembershipProvider来验证用户?我尝试手动调用"验证",但这并未使用户登录。

这是我正在使用的代码片段

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
    }
}

解决方案

回答

验证成功后,我们需要通过调用FormsAuthentication.Authenticate登录用户:http://msdn.microsoft.com/zh-cn/library/system.web.security.formsauthentication.authenticate.aspx

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

另外,要将用户重定向回他想去的地方,请致电:FormsAuthentication.RedirectFromLoginPage:http://msdn.microsoft.com/zh-cn/library/system.web.security.formsauthentication.redirectfromloginpage.aspx

连结文字

回答

如果验证成功,则可以设置自己的" 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  
    }   
}