Using Custom MembershipProvider without a Login control in ASP.NET
-
09-06-2019 - |
Question
We have got a custom MembershipProvider
in ASP.NET
. Now there are 2 possible scenario the user can be validated:
User login via
login.aspx
page by entering his username/password. I have used Login control and linked it with theMyMembershipProvider
. This is working perfectly fine.An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in
MembershipProvider.Validate(string authenticationToken)
, which is actually validating the user. In this case we cannot use the Login control. Now how can I use the sameMembershipProvider
to validate the user without actually using the Login control? I tried to callValidate
manually, but this is not signing the user in.
Here is the code snippet I am using
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
}
}
Solution
After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx
EDIT: It is FormsAuthentication.SetAuthCookie: http://msdn.microsoft.com/en-us/library/twk5762b.aspx
Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx
OTHER TIPS
You can set your own FormsAuthenticationTicket
if the validation is successful.
Something like this;
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
}
}
You are right in the case of storing the auth information as a cookie directly. But using a strong hash function (e.g. MD5 + SHA1) is great and secure. By the way, if you use sessions (which is also just a hash cookie) you could attach auth information to it.