我翻译的:Roles-Based Authentication By Zek3vil

Roles-Based Authentication By Zek3vil

Sample Image - screenshot.gif

介绍

这篇文章演示了如何在ASP.NET中使用窗体验证。 我写了一些类和一个小的WEB应用程序作为例子。这个小程序有四个窗体(页)用来完成以下功能: 添加新用户, 给用户赋予角色, 从普通用户和管理员角色中移除角色。尽管我写的这些类提供了足够多的已经可以使用的功能,出于示范的目的,我限制了用户类的域。这意味着用户可以提供一些基本的域当注册一个新的帐号,例如:姓名,邮件,密码,个人介绍。如果你想的话,你也可以添加一些域这非常简单。

这四个类分别是: User, Role, SitePrincipalSiteIdentity.下面是这四个类的方法和属性:

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

使用窗体验证

要使用 ASP.NET Forms Authentication, 你的应用程序的 web.config 文件必须包含以下内容:

<configuration>
     <system.web>
      <authentication mode="Forms">
            <forms name="RolesBasedAthentication" 
                path="/" 
                loginUrl="/Login.aspx" 
                protection="All" 
                timeout="30">
            </forms>
         </authentication>
     </system.web>
</configuration>

authentication mode 设为 Forms, this enables the Forms Authentication for the entire application. name 属性的值 is the name of the browser cookie, 缺省值为.ASPXAUTH 但是你可以提供一个唯一的名字如果你在同一个服务器上配置了多个应用程序。loginUrl 是你login页的地址. 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, 每次用户请求一个页面, the form will attempt to look up for a cookie in the user's browser. 如果找到了, the user identity was kept in the cookie represented in the FormsIdentity 类. 这个类包含了通过验证的用户的以下信息:

  • AthenticationType - returns the value Forms
  • IsAthenticated – 返回一个boolean值来指示 indicating where the user was authenticated
  • Name – 指示以通过验证的用户的name

因为FormsIdentity 仅包含用户的Name  而有时你需要更多的信息。这就是为什么我写了 SiteIdentity类。 这个类 implements the IIdentity 接口,包含了关于通过验证的用户的更多的信息。

创建 Login 页面

为了创建login 页面, 你仅仅需要两个 textboxes ,用来让用户输入邮件地址 和密码。 将它们分别命名为 EmailPassword。 你可以用一个 check box 来询问用户是否需要设置一个永久的 cookie, 最后添加一个 submit 按钮和它的 OnClick 事件 :

private void Submit_Click(object sender, System.EventArgs e)
{
      // 调用 ValidateLogin 静态方法来检查电子邮件地址和密码是否            
      // 正确。如果正确,这个方法将返回一个新的用户,否则返回null
      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;
        // 将邮件地址放到 cookie 
        // true 代表 cookie 被设为永久保存
        FormsAuthentication.SetAuthCookie( Email.Text, true ); 
        // 将用户重新定位到主页 
        Response.Redirect("Default.aspx");
    }
}

以上的代码是简单易懂的。首先我们调用 SitePrincipal.ValidateLogin() 来查询数据库  判断用户是否输入了挣钱的邮件地址和密码。并且返回一个SitePrincipal 对象的新实例。 如果新的对象是 null 就意味着用户没有输入正确的邮件或密码,否则我们分配给当前的用户一个新的对象。然后设置 cookie 并将用户重新定位到主页.

对每一个请求验证用户

无论何时用户请求一个页面, ASP.NET Forms Authentication 将自动获取 cookie. 但是我们But we haven't replaced the current context user with our own, 因此我们要创建一个 pagebase 类作为基类 and replace the current context user with our own 所以源自pagebase 的每一个页面都将拥有我们自己的SitePrincipal 实例作为用户上下文。When the SitePrincipal is instantiated, 它将自动寻找匹配当前用户的角色并将它分配给这个用户。 以下代码创建一个 pagebase 类,并替代 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;
            }    
    }
    }
}

因此现在每一页都源自这一基类而不是源自System.Web.UI.Page. 因此,如果你想要得到当前以通过验证用户的用户名、密码或者邮件地址或 user ID,你可以按照以下方法来做:

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;
}

或者,你可以使用以下方法来判断当前用户是否属于一个特定的角色:

if (Context.User.Identity.IsAuthenticated) 
{
    // 如果用户不属于 Admin 角色,
    // /她将被重新定位到login 页面
    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.

 

posted on 2004-10-11 21:20  THETOP  阅读(265)  评论(0)    收藏  举报

导航