惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google DeepMind News
Google DeepMind News
T
Tenable Blog
博客园_首页
S
Securelist
Spread Privacy
Spread Privacy
Google Online Security Blog
Google Online Security Blog
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
U
Unit 42
L
LINUX DO - 热门话题
量子位
T
Threat Research - Cisco Blogs
博客园 - 【当耐特】
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
Martin Fowler
Martin Fowler
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
Know Your Adversary
Know Your Adversary
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
T
The Blog of Author Tim Ferriss
aimingoo的专栏
aimingoo的专栏
V2EX - 技术
V2EX - 技术
T
Tailwind CSS Blog
月光博客
月光博客
Recent Announcements
Recent Announcements
G
Google Developers Blog
F
Full Disclosure
W
WeLiveSecurity
宝玉的分享
宝玉的分享
腾讯CDC
G
GRAHAM CLULEY
Vercel News
Vercel News
Simon Willison's Weblog
Simon Willison's Weblog
美团技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Help Net Security
Help Net Security

博客园 - Ekin.S.Sun

document.execCommand Web文件ContentType类型大全 ArcGIS符号库制作过程说明 JavaScript中的一些重要却容易被忽视的东西 AJAX and the ASP.NET 2.0 Callback Framework My heart hurt:( Working with the ArcGIS Server ArcObjects API : ArcObjects API Js网页打印处理 c#和js的交互(转) MapInfo格式到ArcGIS格式的转换方法 ArcGIS Server 9.2建立的web Application实现打印的一篇文章。 .net学习站点推荐 AJAX .Net组件用户指南(译文&原文) New characteristic of Visual Studio 2005 ASP.NET中常用发送邮件功能代码总结 C#常用正则表达式 ASP.NET系统用户权限设计与实现 web.config文件详解 [转] 软件测试的一些认识
how to use Form Authentication in ASP.NET.
Ekin.S.Sun · 2007-01-25 · via 博客园 - Ekin.S.Sun

Sample Image - screenshot.gif

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



SitePrincipal newUser =
SitePrincipal.ValidateLogin(Email.Text, Password.Text);
if (newUser == null)
{
ErrorMessage.Text = "Login failed for " + Email.Text;
ErrorMessage.Visible = true;
}
else
{

Context.User = newUser;


FormsAuthentication.SetAuthCookie( Email.Text, true );

Response.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:

if (Context.User.Identity.IsAuthenticated)
{
string name = ((SiteIdentity)Context.User.Identity).FullName;
string email = ((SiteIdentity)Context.User.Identity).Email;
string password = ((SiteIdentity)Context.User.Identity).Password;
string userID = ((SiteIdentity)Context.User.Identity).UserID;
}

Or if you can check if the current user is in a specific role as following:

if (Context.User.Identity.IsAuthenticated)
{


if (!((SitePrincipal)Context.User).IsInRole("Site Admin"))
Response.Redirect("Login.aspx");
}

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.