How to handle "Remember me" in the Asp.Net Membership Provider - asp.net

Ive written a custom membership provider for my ASP.Net website.
Im using the default Forms.Authentication redirect where you simply pass true to the method to tell it to "Remember me" for the current user.
I presume that this function simply writes a cookie to the local machine containing some login credential of the user.
What does ASP.Net put in this cookie? Is it possible if the format of my usernames was known (e.g. sequential numbering) someone could easily copy this cookie and by putting it on their own machine be able to access the site as another user?
Additionally I need to be able to inercept the authentication of the user who has the cookie. Since the last time they logged in their account may have been cancelled, they may need to change their password etc so I need the option to intercept the authentication and if everything is still ok allow them to continue or to redirect them to the proper login page.
I would be greatful for guidance on both of these two points. I gather for the second I can possibly put something in global.asax to intercept the authentication?
Thanks in advance.

For me the solution was differentiating between a browser-session auth cookie (not to be confused with the asp.net session cookie) and a persistent one - setting a low expiration will create a persistent cookie meaning it gets remembered when the browser is closed and re-opened within the expiration time. The following works for me:
public void SetAuthenticationCookie(LoginView loginModel)
{
if (!loginModel.RememberMe)
{
FormsAuthentication.SetAuthCookie(loginModel.Email, false);
return;
}
const int timeout = 2880; // Timeout is in minutes, 525600 = 365 days; 1 day = 1440.
var ticket = new FormsAuthenticationTicket(loginModel.Email, loginModel.RememberMe, timeout);
//ticket.
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted)
{
Expires = System.DateTime.Now.AddMinutes(timeout),
HttpOnly = true
};
HttpContext.Current.Response.Cookies.Add(cookie);
}

FormsAuthentication and MembershipProviders are two completely different things, still they are made to work with each other very well. If you have written a persistent cookie ["Remember Me"] then next time, you can simply call Membership.GetUser() which will return you the MembershipUser instance of the currently logged in user or null if no user is logged in.
So first time when user arrives and authenticates with "Remember Me", you shall write a persistent cookie as following.
FormsAuthentication.RedirectFromLoginPage(strUserName, true);
Assuming user does not logout and leaves webpage and comes back after sometime. You can simply call MembershipUser.GetUser() as following and check if the user is already logged from the persistent cookie written by FormsAuthentication.
MembershipUser someUser = Membership.GetUser();
if(someUser == null)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
else
{
//Take where logged in users go.
}
You can do this check on your Login page itself or main landing page to intercept the User account to check if he needs to change the password or if the account is disabled as in your case.
EDIT
There are two ways to do this.
1.) Check for authentication as mentioned above in Session_Start event in global.asax and set a session key that becomes available on all pages for that particular session.
2.) Another way is too keep a common application wide common PageBase class that inherits from System.Web.UI.Page and acts as base page class for all your asp.net pages. On the Page Load of the common PageBase class check for the authentication as mentioned above. You will have to carefully write conditional redirection in this case since this might head towards infinite redirection with no end since it will run on Page_Load of all page from the common PageBase class.
public class PageBase : System.Web.UI.Page
{
/// <summary>
/// Initializes a new instance of the Page class.
/// </summary>
public Page()
{
this.Load += new EventHandler(this.Page_Load);
}
private void Page_Load(object sender, EventArgs e)
{
try
{
AuthenticateUser();
}
catch
{
//handle the situation gracefully.
}
}
private AuthenticateUser()
{
MembershipUser someUser = Membership.GetUser();
if(someUser == null)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
else
{
//Take where logged in users go.
}
}
}
//in your asp.net page code-behind
public partial class contact : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
}
}

Related

ASP.NET session stateid issue

i have a load balancing application, and we have an issue where a user try to log in, he/she will then see some else's name.
during the logout process we only call "Session.Abandon();". The article in http://support.microsoft.com/kb/899918 states the following:
When you abandon a session, the session ID cookie is not removed from
the browser of the user. Therefore, as soon as the session has been
abandoned, any new requests to the same application will use the same
session ID but will have a new session state instance. At the same
time, if the user opens another application within the same DNS
domain, the user will not lose their session state after the Abandon
method is called from one application.
does anyone have a clue of why the user sees some else's name while loging in?
Edited - code:
public class CacheManager
{
public Contact.Contact User
{
get { return HttpContext.Current.Session["Contact"] as Contact.Contact; }
set { HttpContext.Current.Session["Contact"] = value; }
}
}
header.ascx.cs
/// <summary>
/// This is the session manager
/// </summary>
public readonly CacheManager Localcache = new CacheManager();
public Login()
{
var contact = BAL.Contact.Get(this.UserName, this.Password);
Localcache.User = contact;
Response.Redirect(Request.Url.AbsoluteUri);
}
protected void Logout_Click(object sender, ImageClickEventArgs e)
{
Session.Abandon();
Response.Redirect(Constants.HomePage);
}
header.ascx:
You are logged in as
<br />
<span class="user_desc">
<%= string.Format("{0} {1}",LocalCache.User.FirstName ,LocalCache.User.LastName)%></span>
when a user explicitly logs out and a new user accesses the page (assuming the browser wasn't closed), the browser still maintains the sessionId (even with Session.Clear() and Session.Abandon()).
Try to add these lines of code
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
Link to check

ASP.NET membership - Redirect users with unpaid invoice

I'm working on a custom implementation of ASP.NET membership, which uses my own database tables. Everything works as it should, but I need to redirect customers, which have not paid their invoice, to a payment page. This should not only happen on login, but also for users which already are logged in, so if an invoice is registered as "not paid" while the user is logged in, then the user must be redirected to the payment page, the next time they load a page.
Can this be done?
I did something similar to this using a HttpModule. What you want to do is handle the PreRequest event and if they are authenticated and if so make your unpaid invoice check and redirect as necessary.
e.g.
protected void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Path != "/UnPaid.aspx" && HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// You don't want to make this check for every resource type
bool isPage = HttpContext.Current.Request.Path.EndsWith(".aspx") || HttpContext.Current.Request.Path == "/";
if (isPage)
{
bool isPaid = false; // Make isPaid check here
if (!isPaid)
{
// Optional pass ina return url for after the invoice is paid
string returnUrl = HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl, HttpContext.Current.Request.ContentEncoding);
HttpContext.Current.Response.Redirect(string.Concat("/UnPaid.aspx?ReturnUrl=", returnUrl), true);
}
}
}
}
}
I wouldn't let the membership provider know this information. It is job of your application to know this, not your security model. It may be as simple as adding/removing a role, but that's not ideal either.
You can do that on global.asax using the Application_AuthenticateRequest
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
if(!cTheFile.EndsWith("ThePaymentPage.aspx"))
{
if(HttpContext.Current.User != null
&& HttpContext.Current.User.Identity != null
&& HttpContext.Current.User.Identity.IsAuthenticated)
{
// check here if need to redirect or not.
if(NeedPayment())
{
HttpContext.Current.Responce.Redirect("ThePaymentPage.aspx");
}
}
}
}
This is called on every page, so maybe you can add some more checks and make it real fast. Other checks can be if the page ends on .aspx
How about having inheritance.
You can "inject" a BasePage between Page class and your ASPX code behind class.
This way, you will have access to your business logic classes and then you can decide, on each request, where the user should be re-directed.
Me too agree on the point that this logic should be handled by your applications business logic instead of the security model.
Hope this helps.

Custom authentication module inheriting IHttpModule issue

LoginPage.aspx:-
protected void Button1_Click(object sender, EventArgs e)
{
Context.Items["Username"] = txtUserId.Text;
Context.Items["Password"] = txtPassword.Text;
//
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Context.Items["Username"].ToString(), DateTime.Now, DateTime.Now.AddMinutes(10), true, "users", FormsAuthentication.FormsCookiePath);
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
Response.Redirect("Default.aspx");
}
Global.asax file:-
void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
Response.Write(HttpContext.Current.User.Identity.Name);
Response.Redirect("Default.aspx");
}
}
}
}
I get the following error after signing in
This webpage has a redirect loop.
The webpage at http://localhost:1067/Default.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
This is the rough idea of what your module should look like. Your module will run on every request. You don't invoke it or pass anything to it, it just automatically fires whenever a request is made that ASP.Net is set to process.
Your module will do two things, 1) authenticate a user in the login page, 2) authenticate a user on subsequent pages. The first step is to subscribe to the BeginRequest method which will be given the current HttpApplication as the first parameter. From there you need to determine if the user is on your login page or not. If they're not on your login page, check your session or cookie or querystring token, or whatever you're using to make sure that they're still valid. If they're invalid, bounce them back to the login page.
If they're on your login page and have made a POST, look at the raw form fields and validate them. TextBoxes, checkboxes, etc don't exist here, only raw form fields. If they're valid, set your authentication token however you want (session, cookies, etc). If they're invalid, either redirect to the login page or inject a "try again" message or something.
Also, if you double-post a message please reference it so that we can follow the chain of what was already said.
class MyModule : IHttpModule
{
void IHttpModule.Init(HttpApplication context)
{
//Subscribe to the BeginRequest event
context.BeginRequest += new EventHandler(this.Application_BeginRequest);
}
private void Application_BeginRequest(Object source, EventArgs e)
{
//Initialize our variables, null checks should be put here, too
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
System.Web.SessionState.HttpSessionState s = context.Session;
//Normally our module needs to validate every request to make sure our request is still authenticated.
//The exception to that rule is on our logon page where they obviously don't have credentials yet.
if(!context.Request.FilePath.ToLowerInvariant().StartsWith("/login.aspx")){
//If we're here then we're not on the logon page, validate our current session according to whatever logic we want
if (s != null && s["isvalid"] == "true"){
return;
}else{
context.Response.Redirect("/login.aspx");
}
}else{
//If we're here then we're on the login page itself. If there's a post, assume that they've hit the login button
if (context.Request.HttpMethod == "POST")
{
//Whatever your form variables are called
string username = context.Request.Form["username"];
string password = context.Request.Form["password"];
//Your own validation logic would go here
if (MyCustomLogin.IsUserValid(username, password))
{
s["isvalid"] = "true";
context.Response.Redirect("/Home.aspx");
}else{
s["isvalid"] = "false";
context.Response.Redirect("/login.aspx?error=invalid_login");
}
}else{
//If we're here then the request is probably a GET or HEAD which would be from a person
//initially browsing to our page so just do nothing and pass it through normally
}
}
}
}
There is no direct way to have access to this information in the module (for authenticated user, you can access the username via the context, but not the password). The module checks if a request is carrying required authentication information and serve or deny the request based on that. Unless you deliberately from the login page collect this information and store somewhere where you can access it in the module, e.g session. But ideally, storing password is not widely recommended, collect it use it for authentication and destroy.
You might ideally throw more light on the reason why you want to have access to this information in the module and guys can then suggest methods to accomplish it.
Edited, after Chandan comment:
#Chandan, your comment here suggest to me what you want to do is use httpmodule for your authentication as against using standard form authentication. If I am on track, then you can check this project on codeproject at http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx. Goodluck

Is there any way to get the requesting user's ID in an ASP.NET web service method?

I know this probably isn't possible, but I would like to be able to get the Request user ID from within an ASP.NET web service method. So far, I've tried User.Identity.Name, Context.Request.LogonUserIdentity.Name, Request.ServerVariables["AUTH_USER"] and Request.ServerVariables["LOGON_USER"]. Am I tilting at windmills here, or is there something super simple that I'm missing?
Well, what do you mean by User ID?
If they've authenticated via Windows Authentication, User.Identity gives you the WindowsIdentity object that corresponds to that user.
If you want the User ID which corresponds to an authenticated user to "magically" show up in your pages, you can do that too! In your Global.asax, there is a function called Application_AuthenticateRequest which you implement to take whatever identity is passed to your application and turn it into a IPrincipal-based object which can be accessed from your pages.
So when you implement AuthenticateRequest(), you can take the HttpContext.Current.User.Identity.Name, and use that to look up your User ID from your database. From there, you construct your own IPrincipal-derived object and set the HttpContext.Currrent.User reference to that object you create. You can then cast "User" in your pages over to the object you create and read the User ID. We do this all the time. Here's some sample code (which actually caches the Principal object so that you don't have to go to the DB on every request):
protected void Application_AuthenticateRequest(object sender, EventArgs e) {
try {
IIdentity myIdentity = HttpContext.Current.User.Identity;
MyPrincipal myPrincipal = (MyPrincipal)HttpContext.Current.Cache[myIdentity.Name];
if (myPrincipal == null) {
myPrincipal = (MyPrincipal)GetPrincipalFromDatabase(HttpContext.Current.User.Identity);
HttpContext.Current.Cache.Insert(myIdentity.Name, myPrincipal, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);
}
HttpContext.Current.User = myPrincipal;
}
catch (SecurityException) {
HttpContext.Current.User = null;
}
catch (Exception ex) {
Trace.WriteLine("Could not validate your user.");
}
}

How to set Thread.CurrentPrincipal for use throughout the application?

In an ASP.net application I'm using a Login control with a custom membership provider that I wrote. What I want to do is to set Thread.CurrentPrincipal to my custom Principal object, just after the user is authenticated.
I'm using the setter: Thread.CurrentPrincipal and it sets the Principal object for me but, on all the consequent threads this CurrentPrincipal is overridden with the default one.
Here is my code for the Authenticate event of the Login control:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username = Login1.UserName;
string password = Login1.Password;
if (Membership.ValidateUser(username, password))
{
var login = sender as Login;
var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true);
var principal = new PhoenixPrincipal(phoenixIdentity);
Thread.CurrentPrincipal = principal;
AppDomain.CurrentDomain.SetThreadPrincipal(principal);
HttpContext.Current.User = principal;
e.Authenticated = true;
}
}
For example, imagine that I login with the username A, everything goes well... Validation passes, but I hardcode the user with the username B in the Identity object which is set to the Principal object I set as the CurrentPrincipal object.
When I check which user is set to the CurrentPrincipal Identity at the end of this method it says it's user B. But when I load another page and then check what the Identity of the CurrentPrincipal is, it says it's user A.
So, how can I make my CurrentPrincipal object to be persistent across all other threads, and where/when does this Login control set the CurrentPrincipal object of the Thread?
Tadas is not wrong, FormsAuthentication correctly implemented will not cause this problem.
Your page is accessible even without login, only in the login page, your thread's principle is set manually by you, but when you hit the other URL, it sure doesnt call your login page and remember each page runs on its own different thread. If you request first page and set thread principle and you request second page in same browser instance, it may or may not be the exact same thread.
This is how FormsAuthentication works,
It checks if Auth Cookie is set or not, it then directs user to login page
Login page must validate and set auth cookie, like FormsAuthentication.SetAuthCookie
Before every page access, Step 1 is executed.
After successful validation of Auth Cookie, ASP.NET internally sets the current user and all differnet parameters according to your membership component.
ASP.NET Global.asax file can give you some events where in you can plugin your code to check just after authentication is successful you can change your current user, remember setting your current principle on login page will not help
We had similar issue when we were using session to store certain important information, after auth sessions were not rebuilt, so we wrote a HTTP Module, and in it's init method, we attached AfterRequestAcquired event and in this event you can write your code to instantiate all your important user related variables.
You can handle FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) (in Global.asax) and set CurrentPrincipal here.
void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e)
{
var phoenixIdentity = new PhoenixIdentity("B", "Forms" , true);
var principal = new PhoenixPrincipal(phoenixIdentity);
e.User = principal;
}
This is what I did in FormsAuthentication_OnAuthenticate method:
if (FormsAuthentication.CookiesSupported)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
var myIdentity = new GenericIdentity("B");
var principal = new GenericPrincipal(myIdentity, new string[]{"rola1"});
e.User = principal;
}
catch (Exception ex)
{
// Decrypt method failed.
}
}
}
else
{
throw new HttpException("Cookieless Forms Authentication is not " +
"supported for this application.");
}
it seems that it's working what it should do... It's just that if I put my custom principal/identity pair as e.User, then I have serialization problem which I need to fix next... Thank you guys...

Resources