how to use Form Authentication in ASP.NET.

來源:互聯網
上載者:User
  • 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 functions that are ready to use, for the demonstration purpose, I have limited the fields in the User 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 and SiteIdentity. I would like to overview the classes' methods and properties here:

The User class
User() Default parameter less constructor to create a new user
User(int userID) This constructor gets a userID 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 returns a DataSet of all the users available in the database
GetRoles() This method returns a DataSet of roles assigned to the current user
GetUserRoles(int userID) This static method grabs the userID and returns a roles ArrayList assigned to that user
AddToRole(int roleID) This method assigns a role to the current user
RemoveFromRole(int roleID) This method removes current user from the role that has been passed by the roleID.
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(int roleID) This constructor gets a roleID and looks up the role details from the database
GetRoles() This method returns a DataSet 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(int userID) This constructor gets a userID 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 returns true
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 application web.config file 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 should provide a unique name if you are configuring 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 in the FormsIdentity class. This class contains the following information about the authenticated user:

  • AthenticationType - returns the value Forms
  • IsAthenticated - returns a boolean value indicating where the user was authenticated
  • Name - Indicates the name of an authenticated user

Because the FormsIdentity contains only the Name of the user and sometimes you need more than that, that's why I have written the SiteIdentity which implements the IIdentity 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, named Email and Password, respectively. You may need 1 check box to ask if the user wants us to set a persistent cookie, and finally one submit button with OnClick event which is handled as follows:

Collapse
private void Submit_Click(object sender, System.EventArgs e){// call the ValidateLogin static method to// check if the email and password are correct// if correct the method will return a new user else return nullSitePrincipal newUser =SitePrincipal.ValidateLogin(Email.Text, Password.Text);if (newUser == null){ErrorMessage.Text = "Login failed for " + Email.Text;ErrorMessage.Visible = true;}else{// assign the new user to the current context userContext.User = newUser;// set the cookie that contains the email address// the true value means the cookie will be set persistedFormsAuthentication.SetAuthCookie( Email.Text, true );// redirect the user to the home pageResponse.Redirect("Default.aspx");}}

The code above is straightforward, first we call SitePrincipal.ValidateLogin() which looks up the database and check if the user has entered the correct email and password and returns the new instance of SitePrincipal object. If the new object is null 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 should create a pagebase class as base class and replace the current context user with our own so that every page that is derived from this pagebase will have our own SitePrincipal instance as context user. When the SitePrincipal is instantiated, it will automatically search for roles that match the current user and assign to the user's roles. The code below creates a pagebase 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 should derive this bass class instead of deriving the System.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:

  1. Copy the RolesBasedAthentication.Web folder to the wwwroot directory.
  2. Share the RolesBasedAthentication.Web folder by right clicking and choose Properties and then open the Web Sharing tab and choose Share this folder.
  3. Create a new database and name it RolesBasedAuthentication.
  4. Run the script in the database.sql using Query Analyzer to create tables and stored procedures for the new database.

When running the application, log on with account: admin@site.com and password: admin to have full access. Hope you find this small application helpful.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.