我们有一个习俗 MembershipProviderASP.NET. 。现在有两种可能的情况可以验证用户:

  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
    }
}
有帮助吗?

解决方案

验证成功后,您需要通过调用 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

链接文本

其他提示

您可以自己设置 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  
    }   
}

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top