在 ASP.NET 中使用没有登录控件的自定义 MembershipProvider
-
09-06-2019 - |
题
我们有一个习俗 MembershipProvider
在 ASP.NET
. 。现在有两种可能的情况可以验证用户:
用户登录通过
login.aspx
输入他的用户名/密码即可进入页面。我用过 登录控制 并将其与MyMembershipProvider
. 。这工作得很好。身份验证令牌通过不同网站的查询字符串中的某个 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),您可以将身份验证信息附加到它。