I am using the asp.net CreateUserWizard and I have LoginCreatedUser=true. I also have the "OnCreatedUser" property for the CreateUserWizard control to a method and thought the auth ticket would be created at that point but it is not.
When exactly is the authentication ticket (Request.Cookies[".ASPXAUTH"]) populated?
I need to know so that during registration I can modify the UserData and add it to the auth ticket.
I've done this before doing the following:
In the CreateUserWizard_CreatedUser event you know for a fact the user is created, so save the username to HttpContext.Items array.
Check for the username in HttpContext.Items in the page's PreRender() event (it'll run after the CreatedUser() step). If it's there overwrite your authentication ticket
To test this make sure you later decrypt the authentication ticket and check the UserData. In my own projects this is how I handle having a user logged in at registration and have some of their info injected into the auth ticket's UserData.
Related
In MVC5 asp.net - Is there a way to allow user login only if the user has a particular claim in the user database? I'd like to assign a "CanLogin" claim to users in my user database that are allowed to log in at any given time. By removing the "CanLogin" claim, I could effectively lock the users out of the system until further notice.
This would have to work for a first time login as well as cookie login at a later stage if the user has checked "remember my login".
Using authentication filter, you can check the identity.claims property to validate whatever claims are present in the context.
The claims must be added during the login process
Then you can check whether a particular user is enabled or not.
However, if the user database is self maintained, you can just set a disabled flag and then reject the login request, instead of returning such a claim.
The claims are used for Authorization to a particular functionality rather than Authentication to an app. A valid user will have certain claims which can tell what all the user is permitted to do.
I have an ASP.Net MVC3 app. When the LogIn action is called, I use the MembershipProvider to validate the user and FormsAuthentication to set the cookie.
Additionally, I get some info about the user from a database and store it in Session.
When the user subsequently visits the site, they're already authenticated via the cookie, and I'm looking for somewhere to hook into so I can fetch the info about the user from the database again.
Is HttpApplication.AuthorizeRequest() the best place to do this? Obviously this is called for every request so I was hoping there was something I could use that just indicated the user had been authenticated - either explicitly after logging in or when they're authenticated automatically.
There are several events that get triggered on every request, HttpApplication.AuthorizeRequest() should work.
In order to only fetch from the database for logged in users, you can check the Name property of User.Identity which only gets set once the user authenticates:
if(!string.IsEmpty(User.Identity.Name))
{
//make call to database
}
I made a custom membership provider and overrode the ValidateUser method, but now I am confused. I am not using any Login controls, I just have a site wide login (username and password box) on a masterpage.
Questions:
Do I need to call the ValidateUser() method myself? If so, what are
the next steps to take? Do I create the auth cookie which methods do I need to call to complete the login?
I need to return some custom user data if the user is authenticated. Is it better to
call GetUser and check for null or just call ValidateUser and then
grab a user object?
Where and how should I store the custom data for the user? Is it stored in the identity object? Should I store it in the MembershipUser Object?
Yes, you verify that the credentials are correct by doing a call such as
Membership.ValidateUser(TextBoxUsername.Text, TextBoxPassword.Text)
If the above call returns true then you need to set the authentication cookie like so:
FormsAuthentication.SetAuthCookie(TextBoxUsername.Text, CheckboxRememberMe.Checked);
There I used a "remember me" checkbox if you want to login automatically next time.
To get the user details you can call
Membership.FindUsersByName(TextBoxUsername.Text)
The most handy place you can store the user details is the session.
You didn't ask, but just as important would be a log out page. The functionality needed to undo the login steps are:
FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect("~/login.aspx", false);//or homepage, or any other page
I am reading on form authentication in ASP.NET and cannot understand some moment:
James enters a username-password, they are saved in the db. A cookie from username is created, encrypted and attached to a response. As I understand then, when we get a request we need to recognise that cookie received are from James and so we can show his customised page.
What I would like to understand is how system will retrieve username form cookie and then load his info from db?
Forms Auth is storage agnostic. It doesn't have to use a database, indeed you can use it with usernames and passwords in web.config.
So what happens is
A user logs in.
The user is authenticated against the membership provider (which can use SQL, Active DIrectory, web.config, Oracle, MySQL, whatever)
A forms authentication token is created for the user, and is placed on the user machine via a cookie.
Each subsequent request reads the forms authentication token, and queries the provider to get the user details.
The user details are used to populate the user identity in the HttpContext and current thread for the request which is then available to your code to use.
In your code you can check the User property in the Page class (WebForms) or the User property in the controller class (MVC).
While you can get at it via the current thread, or the current context it's not advised, especially once you start using background tasks, where the identity may not propagate to the thread, or the context may change.
You'll note that nothing is stored in a database when the user logs in. It's all in the forms authentication token, and the work of retrieving the user from it's store on each request is done for you.
Afaik Forms Authentication does not store or load anything in any database. You can use a database to store the username and password, or you can put them in the web.config. How you store user credentials and validate them is up to you, and can happen separately from Forms Authentication.
Once you have validated a user (against database or some other logical storage), you use FormsAuthentication to write the authentication cookie. You do not need to worry about decrypting the cookie.
You can get the username from System.Threading.Thread.CurrentPrincipal.Identity.Name. To retrieve user's info from the database, you would query the database using the value if the principal identity name.
Response to comments
Right, you can use forms authentication with the membership provider, active directory, or your own custom user database. FormsAuth doesn't care about the password at all, unless it is stored in web.config (as noted in blowdart's more complete answer). It just writes the cookie, which is decrypted and used to create the thread identity automatically.
Additional Info
Even though this was marked as the answer, blowdart's response is much more complete. You really should not get the identity from the thread if you need it in an ASPX page or MVC controller, use the properties he referenced.
You get the username in your web form by calling User.Identity.Name, e.g. like this:
protected void Page_Load(object sender, EventArgs e)
{
string userName = User.Identity.Name;
}
ASP.NET interprets the cookie for you, you don't have to read it yourself. Or is your question how to store the user and password in the DB?
Using Forms Authentication, I am storing a cookie for each user if they mark Remember Me during login, using the following piece of code in the Login1_LoggedIn event.
if (rememberMe.Checked) FormsAuthentication.SetAuthCookie(Login1.UserName, true);
When the user arrives on my page with a cookie, I need to get his/her user name so I can check their roles. Does the Forms Authentication cookie store this information, and how can I retrieve it?
The string you parse to SetAuthCookie (Login1.UserName in your case) will be stored in the IPrincipal when the user accesses a page. You can access it using:
Page.User.Identity.Name
Try
Page.User.Identity.Name
or
HttpContext.Current.User.Identity.Name