- Download source files-43.1 KB
- Download Demo project-21.9 KB
Introduction
This article demonstrates how to use form authentication in ASP. net. I have written a set of classes and a small web application that uses these classes as an example. the small application features 4 forms (pages) that allow you to do the following functions: Add new user, assign roles to users, remove roles from users and Manage Roles. although the classes I 've written provide quite enough funugh that are ready to use, for the demonstration purpose, I have limited the fields inUser
Class. that means users can provide some basic fields when registering for a new account: full name, email, password, biography. you can add more fields later if you want, it's quite easy.
The classes Overview
There are 4 classes:User
,Role
,Siteprincipal
AndSiteidentity
. I wowould like to overview the classes 'Methods and properties here:
The user class
User () |
Default parameter less constructor to create a new user |
User (IntUserid) |
This constructor getsUserid And looks up the user details from the database |
User (string email) |
This constructor gets an email and looks up the user details from the database |
Getusers () |
This method returnsDataset Of all the users available in the database |
Getroles () |
This method returnsDataset Of roles assigned to the current user |
Getuserroles (IntUserid) |
This static method grabsUserid And returns a rolesArraylist Assigned to that user |
Addtorole (IntRoleid) |
This method assigns a role to the current user |
Removefromrole (IntRoleid) |
This method removes current user from the role that has been passed byRoleid . |
Add () |
Adds a new user to the database |
Update () |
Updates current user information |
Delete () |
Deletes current user |
Userid |
Gets/sets user's ID number |
Fullname |
Gets/sets user's full name |
Email |
Gets/sets user's email |
Password |
Gets/sets user's password |
Biography |
Gets/sets user's biography |
Dateadded |
Gets/sets user's registering date |
The role class
Role () |
Default parameter less constructor to create a new role |
Role (IntRoleid) |
This constructor getsRoleid And looks up the role details from the database |
Getroles () |
This method returnsDataset Of all roles available in the database |
Add () |
Adds a new role to the database |
Update () |
Updates current role information |
Delete () |
Deletes current role |
Roleid |
Gets/sets role ID number |
Rolename |
Gets/sets role name |
The siteprincipal class (implements the iiprincipal Interface)
siteprincipal ( int userid) |
This constructor gets a userid and looks up details from the database |
siteprincipal (string email) |
This constructor gets an email and looks up details from the database |
isinrole () |
( iiprincipal. isinrole () ) indicates whether a current principal is in a specific role |
validatelogin () |
adds a new user to the database |
identity |
( iiprincipal. Identity ) gets/sets the identity of the current principal |
roles |
gets the roles of the current principal |
The siteidentity class (implements the iidentity Interface)
Siteidentity (IntUserid) |
This constructor getsUserid And looks up the user details from the database |
Siteidentity (string email) |
This constructor gets an email and looks up the user details from the database |
Authenticationtype |
(Iidentity. authenticationtype ) Always returns"Custom Authentication " |
Isauthenticated |
(Iidentity. isauthenticated ) Always returnsTrue |
Name |
(Iidentity. Name ) Gets the name of the current user |
Email |
Gets the email of the current user |
Password |
Gets the password of the current user |
Userid |
Gets the user ID number of the current user |
Enabling Forms authentication
To enable ASP. NET Forms authentication, your applicationWeb. configFile must contain the following information:
<Configuration> <system. web> <Authentication mode = "forms"> <forms name = "rolesbasedathentication" Path = "/" loginurl = "/login. aspx "Protection =" all "timeout =" 30 "> </Forms> </authentication> </system. web> </configuration>
the Authentication mode is set to forms
, this enables the forms authentication for the entire application. the value of the name
attribute is the name of the browser cookie, the default value is . aspxauth
but you shoshould provide a unique name if you are using ing multiple applications on the same server. the loginurl
is the URL to your login page. the timeout is the amount of time in minutes before a cookie expires, this attribute does not apply to persistent cookies. the Protection
attribute: Is the way your cookie data is protected, all
means that your cookie data will be encrypted and validated. other values that you can set are: none
, encryption
, Validation
.
When Forms authentication is enabled, each time a user requests a page, the form will attempt to look up for a cookie in the user's browser. if one is found, the user identity was kept in the cookie represented inFormsidentity
Class. This class contains the following information about the authenticated user:
Athenticationtype
-Returns the valueForms
Isathenticated
-Returns a Boolean value indicating where the user was authenticated
Name
-Indicates the name of an authenticated user
BecauseFormsidentity
Contains onlyName
Of the user and sometimes you need more than that, that's why I have writtenSiteidentity
Which implementsIidentity
Interface to contain more information about the authenticated user.
Creating the login page
For creating the login page, you simply need 2 textboxes to let the user input the email address and password, namedEmail
AndPassword
, Respectively. You may need 1 check box to ask if the user wants us to set a persistent cookie, and finally one submit buttonOnclick
Event which is handled as follows:
Collapse
Private Void Submit_click ( Object Sender, system. eventargs e ){ // Call the validatelogin static method // Check if the email and password are correct // If correct the method will return a new user else return null Siteprincipal newuser = siteprincipal. validatelogin (email. Text, password. Text ); If (Newuser = Null ) {Errormessage. Text = "Login Failed" + Email. Text; errormessage. Visible = True ;}Else { // Assign the new user to the current context user Context. User = newuser; // Set the cookie that contains the email address // The true value means the cookie will be set persisted Formsauthentication. setauthcookie (email. Text, True ); // Redirect the user to the Home Page Response. Redirect ( "Default. aspx" );}}
The code above is straightforward, first we callSiteprincipal. validatelogin ()
Which looks up the database and check if the user has entered the correct email and password and returns the new instanceSiteprincipal
Object. If the new object isNull
That means the user has not entered a correct email or password, otherwise we assign the current user with the new object. Then set the cookie and redirect the user to the main page.
Authenticating user on every request
Whenever user requests a page, the ASP. NET Forms authentication will automatically pick up our cookie. But we haven't replaced the current context user with our own, so we shocould createPagebase
Class as base class and replace the current context user with our own so that every page that is derived from thisPagebase
Will have our ownSiteprincipal
Instance as context user. WhenSiteprincipal
Is instantiated, it will automatically search for roles that match the current user and assign to the user's roles. The code below createsPagebase
Class and replaces the current context with our own:
Public Class Pagebase: system. Web. UI. Page { Public Pagebase (){}Protected Override Void Oninit (eventargs e ){ Base . Oninit (E ); This . Load + = New System. eventhandler ( This . Pagebase_load );} Private Void Pagebase_load ( Object Sender, system. eventargs e ){ If (Context. User. Identity. isauthenticated ){ If (! (Context. User Is Siteprincipal) {siteprincipal newuser = New Siteprincipal (context. User. Identity. Name); context. User = newuser ;}}}}
So now every page shocould derive this bass class instead of derivingSystem. Web. UI. Page
. So if you want to get the current name or email address or user ID of the authenticated user, you can do like this:
<SPAN class = "CS-keyword"> If </span> (context. user. identity. isauthenticated) {<SPAN class = "CS-keyword"> string </span> name = (siteidentity) context. user. identity ). fullname; <SPAN class = "CS-keyword"> string </span> email = (siteidentity) context. user. identity ). email; <SPAN class = "CS-keyword"> string </span> Password = (siteidentity) context. user. identity ). password; <SPAN class = "CS-keyword"> string </span> userid = (siteidentity) context. user. identity ). userid ;} |
Or if you can check if the current user is in a specific role as following:
<SPAN class = "CS-keyword"> If </span> (context. user. identity. isauthenticated) {<SPAN class = "CS-comment"> // If user is not in the site admin role, </span> <SPAN class = "CS-comment"> // he/she will be redirected to the login page </span> <SPAN class = "CS-keyword"> if </span> (! (Siteprincipal) context. user ). isinrole (<SPAN class = "CPP-string"> "site admin" </span>) response. redirect (<SPAN class = "CPP-string"> "login. aspx "</span> );} |
The demo application
All the code above is the only base for using my classes to turn your application into a roles-based authentication system. how ever I have written a small demo web application that uses these classes as an example with quite enough functions like: insert/update/delete roles, assign user to roles and remove user from roles. in order to get the application up and running, you need to have SQL Sever, since I'm not using access as a database management system.
You can download the demo application and all the source code for the classes from the links at the top of this page and follow these steps to get the application up and running:
- CopyRolesbasedathentication. WebFolder toWwwrootDirectory.
- ShareRolesbasedathentication. WebFolder by Right clicking and choosePropertiesAnd then openWeb SharingTab and chooseShare this folder.
- Create a new database and name itRolesbasedauthentication.
- Run the script inDatabase. SQLUsingQuery AnalyzerTo create tables and stored procedures for the new database.
When running the application, log on with account:Admin@site.comAnd password:AdminTo Have Full Access. Hope you find this small application helpful.