Getting the session ID causes the user to logout - asp.net

I am observing very strange behaviour in an ASP.NET application I am writing and have reproduced the problem by creating a vanilla application from the VS2013 template and changing one line...
Background
In the LogIn event of the Login.aspx page I retrieve the sessionID from the current Session at the point the user logs in successfully. I do this in the case statement for SignInStatus.Success by adding the following line:
var sessionId = Session.SessionID;
After adding this line I can no longer log in. Typing the username and password just jumps back to the default page without showing the user as signed in.
If I remove that line, sign in works as expected.
To reproduce:
In VS2013, create a new ASP.NET Web Application. Select the Web Forms template. Change Authentication to be Individual User Accounts. Untick Host in the cloud. Untick MVC and Web API.
Once the application is created change LogIn in Login.aspx.cs to start as follows:
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
// This doen't count login failures towards account lockout
// To enable password failures to trigger lockout, change to shouldLockout: true
var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var sessionId = Session.SessionID;
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
After registering a user, log out. Try and sign in again and it won't work.
If you remove the SessionId line again it will let you sign in.

Related

asp.net webforms login with custom database

and thanks in advance for anyhelp you can provide.
My problem is i have this schema for example
table users: id, name, password, category_id | table category: id, name (with client and admin values for example (and dont want to change this schema).
I would like to know what needs to be donne in order to make a login with the default functionalities like the role authorization system of the .net framework.
I have already looked in customMembership and custom roleProvider Implementation, but i get stuck right in the login which uses neither of these two classes.
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
// This doen't count login failures towards account lockout
// To enable password failures to trigger lockout, change to shouldLockout: true
//fails here
var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
...
Do i need to implement an usermanagerProvider?

How to use DotNetOpenAuth to login to websites?

I want to do is, if the users are logged into gmail and if they go to my website they automatically get logged in.
I am doing it in the following way... maybe there is a better way of doing it.
In my website I have a place for uses to give their gmail address so my website knows gamil address of the registered user.
So when they go to my website I want to know whether they are logged into gmail and what is their gmail address.
How should I find this information using DotNetOpenAuth?
I found following code from the web and it is authenticating the user. But i have to press the button and go to gmail login every time.
if the user is already using gmail I don’t have to ask the user for login i can use it.
How do i modify this code to achieve that?
static string openidurl = "https://www.google.com/accounts/o8/id";
protected void Page_Load(object sender, EventArgs e)
{
//The Response
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
var fetch = response.GetExtension<FetchResponse>();
string email = "";
if (fetch != null)
{
email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
}
break;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
{
IAuthenticationRequest request = openid.CreateRequest(openidurl);
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
request.AddExtension(fetch);
// Send your visitor to their Provider for authentication.
request.RedirectToProvider();
}
}
It sounds like what you're asking for is "single-sign-on", where a visitor to your site who is already logged into Google is immediately logged into your site when they first visit it, rather than after clicking a "Google Login" button on your site.
The short answer is you can't do this. The longer answer is that you can get close.
The first and hard restriction is that first-time visitors to your site will never get automatically signed in, because Google and the user don't yet trust your site. Every user has to explicitly log in once, with Google asking the user "do you want to log into this site and remember this choice?" If they say yes, then in the future when the user is already logged into Google and visits your site, they can click the Google Login button on your site and they'll never see Google -- they'll just be immediately logged into your site.
So the next question is how do you remove the requirement on the user to click "google Login". You can accomplish this by when an unauthenticated user visits your site, you can immediately redirect them to your log in page, which will immediately initiate the "Google Login" flow (the OpenIdRelyingParty.CreateRequest(google).RedirectToProvider() call), using "immediate mode". This will fail if the user isn't logged into Google and trust your site, but the impact will be the user won't see a Google login screen if they do trust your site, but will rather be immediately logged in.
You might find my answer useful: What OpenID solution is really used by Stack Overflow?
I've also made a simple blog post about it: http://codesprout.blogspot.com/2011/03/using-dotnetopenauth-to-create-simple.html
My examples are with MyOpenID, but gmail should work the same way. The OpenID provider basically takes care of the log in, including the case when they're already logged in with the provider.
Update:
In an ASP.NET (in this case ASP.NET MVC) application you would create a cookie when the user is successfully logged in and you would check the cookie to determine if the user is logged in. As I said, please see the links above for detailed code examples and an explanation of how it all works. Here are two code samples from the Controller where I demonstrate how to check if the user is logged in:
// **************************************
// URL: /User/LogIn
// **************************************
public ActionResult LogIn()
{
if (User.Identity.IsAuthenticated) // <--- CHECKS IF THE USER IS LOGGED IN
{
return RedirectToAction("Profile", "User");
}
Identifier openID;
if (Identifier.TryParse(Request.QueryString["dnoa.userSuppliedIdentifier"], out openID))
{
return LogIn(new User { OpenID = openID }, Request.QueryString["ReturnUrl"]);
}
else
{
return View();
}
}
[HttpPost]
public ActionResult LogIn(User model, string returnUrl)
{
string openID = ModelState.IsValid?model.OpenID:Request.Form["openid_identifier"];
if (User.Identity.IsAuthenticated)//<--- CHECKS IF THE USER IS LOGGED IN
{
return RedirectToAction("Profile", "User");
}
else if (!string.IsNullOrEmpty(openID))
{
return Authenticate(openID, returnUrl);
}
else if(ModelState.IsValid)
{
ModelState.AddModelError("error", "The OpenID field is required.");
}
// If we got this far, something failed, redisplay form
return View(model);
}

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

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

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

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