Friday, 21 November 2014

Authenticating a user in ASP.NET

For this stage of development, I've rearranged the flow of the site. The user now arrives on the homepage in an anonymous state. They are presented with the option to log in via a button. Clicking the button will take them to a log in form. The form has a hard coded set of accounts that can be authenticated against. If the user authenticates successfully, then they are returned to the homepage, with new content shown to them as a fully authenticated user.

I've been following An Overview of Forms Authentication to help with this.

First of all, I've rearranged the homepage, so that it contains a user status and a button to allow them to login.


Following the 'Log in' button takes the user to a new log in page. For this, I've written some basic functionality that feeds back responses to the user based on their attempts to login using three hardcoded accounts.


When a log in is successful, the function FormsAuthentication.RedirectFromLoginPage is called. This creates a ticket, which marks the user as being logged in to the website. It then returns the user to the website's default page. The MSDN entry for this function explains how to defined which page the user is returned to.

Once the home/default page is reloaded, it can determine who is logged in and display some relevant information to them. In this example, I show the user their name, rather than a 'Logged Out' status if they are logged in. User.Identity.IsAuthenticated and User.Identity.Name allowed me to do this.


While implementing this, I had a problem with User.Identity.IsAuthenticated returning false, even though the user had been logged in. This was because I hadn't properly set Forms to be a valid authentication mode in the Web.Config. An answer on StackOverflow helped me figure out the problem.

This is a start to the authentication process. There's much more to do. For a start, allowing users to create their own accounts, which have a database to be stored in. Also, all of the user's data is currently being broadcast to the server in plain text, it'll be necessary to add some form of security encryption. Finally, the user will need to be able to log out their logged in account.

No comments:

Post a Comment