System.Web.Security

来源:互联网 发布:windows dos2unix安装 编辑:程序博客网 时间:2024/05/14 13:34

System.Web.Security概述

System.Web.Security命名空间提供了asp.net 2.0中的一些安全措施,如登陆用户的身份验证、当前用户的角色管理等。

要了解System.Web.Security的管理机制,需要了解ASP.NET2.0的用户和角色的数据存储过程。ASP.NET2.0通过使用Memership类和Roles类,检索用户并验证用户的角色权限,这些用户和角色信息,通过SqlMembershipProvider和SqlRoleProvider类保存在SQL Server中,也可以使用ActiveDirectoryMembershipProvider和AuhorizationStoreRoleProvider类,将数据存储在ActiveDirectory中。如果将数据保存在其他类型的数据库或数据存储器中,可以使用MembershipProvider和RoleProvider类指定自己的数据源。

在System.Web.Security中,用户和角色是非常重要的部分,任何安全验证都离不开对用户的管理。

System.Web.Security命名空间内的类组成

安全是网站建设的基础。System.Web.Security命名空间内的类,负责管理并提供网站安全的一些常用功能。下面列出System.Web.Security内常用的类及其说明:

ActiveDirectoryMembershipProvider : 为ActiveDirectory中的用户管理提供存储机制

ActiveDirectoryMembershipUser : 管理ActiveDirectory存储区域中的而用户信息

AnonymousIdentificationModule :匿名标识类

AuthorizationStoreRoleProvider : 提供角色信息在各个存储区域的存储机制

DefaultAuthenticationModule : 确保上下文中存在身份验证对象

FileAuthorizationModule : 验证用户是否有访问页面的权限

FormsAuthentication : 身份验证管理类

FormsAuthenticaitonModule : 在Forms验证模式下设置应用程序用户的标识

FormsAuthenticationTicket : 票证管理类

FormsIdentify : 经过Forms身份验证过的用户标识

Membership ; 用户管理类

MembershipProvider : 提供用户资格服务

MembershipUser : 成员信息管理类

PassprotAuthenticationModule : 对Passport身份验证服务的包装

PassportIdentify : 提供有PassportAuthenticationModule使用的类

PassportPrincipal : 通过Passport身份验证的对象

RoleManagerModule:管理当前用户的RolePrincipal实例

RoleProvider : 提供角色管理服务的类

SqlMembershipProvider : 管理SQL Server 数据库中的用户信息

SqlRoleProvider: 管理SQL Server数据库中的角色信息

UrlAuthorizationModule : 判断用户是否具备访问Url的权限

WindowsAuthenticationModule: Windows身份验证模式下的用户标识

WindowsTokenRoleProvider: 通过Windows成员资格获取ASP.NET应用程序的角色信息

从上述列表中可以发现,有关登陆用户验证的类有三种:FormsAuthentication,PassprotAuthentication和WindowsAuthenticaiton

 

匿名标识类:AnonymousIdentificationModule类

AnonymousIdentificationModule了用来管理ASP.NET应用程序的匿名标识。下面将介绍如何获取及使用应用程序的匿名标识。

功能说明:

AnonymousIdentificationModule类可以创建并管理匿名标识,asp.net应用程序用其支持一些匿名功能,如匿名登录状态下的Profile个性化配置。在asp.net2.0中,用户可以匿名访问应用程序,同时应用程序分配给匿名用户一个全局唯一标识(Guid)。通过此标识,用户的一些个性配置得以保存。还可以使用其他方式,将这些匿名状态下的配置,保存到登录后当前用户的配置中。

AnonymousIdentificationModule类只管理匿名用户的标识,而要了解如何实现Profile的匿名保存,则需要具备Profile的相关知识。

语法定义:

AnonymousIdentificationModule类的语法如下:

public sealed class AnonymousIdentificaitonModule:IHttpModule

AnonymousIdentificationModule类只有一种构造方法,但不能在应用程序中使用。asp.net应用程序调用此构造方法,创建AnonymousIdentificationModule类的一个实例。调用该构造方法后,在调用Init方法来初始化新的AnonymousIdentificaitonModule对象。

属性详解:

AnonymousIdentificaitonModule类只有一个属性“Enabled”,通过此属性的值,可以在应用程序中判断是否支持匿名访问。

通常要将应用程序设置为支持匿名访问,需要在Web.Config配置文件中,设定匿名访问的属性值。下面的代码演示了如何在Web.Config中启动匿名访问:

<anonymousIdentification enabled="true"/>

在应用程序中判断是否启动了匿名访问,使用“Enabled”属性,代码如下:

if(AnonymousIdentificationModule.Enabled)

典型应用:AnonymousIdentificatonModule与Profile结合保存匿名用户的个性配置

AnonymousIdentificationModule类用来管理匿名用户的标识,而Profile类用来保存用户的个性配置,本例将使用这两个类,保存匿名用户的个性配置。

本实例要实现的功能是:用户不登陆直接进入页面,定义好前景色和背景色,然后退出应用程序,重新不登录进入页面,页面正确实现匿名用户定义的颜色。

 

<authentication mode="Forms"/><anonymousIdentification enabled="true" /><profile ><properties><add name="bgColor" allowAnonymous="true" /><add name="fgColor" allowAnonymous="true" /></properties></profile>


 

 protected void Page_Load(object sender, EventArgs e)    {        try        {            if (Profile.bgColor.ToString() != "" && AnonymousIdentificationModule.Enabled)            {//读取个性定义并显示                Response.Write("<script type='text/javascript'>document.bgColor='" + Profile.bgColor.ToString()                    + "';document.fgColor='" + Profile.fgColor.ToString() + "';</script>");            }        }        catch (Exception ex) { }    }    protected void Button1_Click(object sender, EventArgs e)    {        if (AnonymousIdentificationModule.Enabled)//判断是否启用匿名标识        {            Profile.bgColor = "Black";//背景色            Profile.fgColor = "Green";//前景色        }    }


 默认身份验证类:DefaultAuthenticationModule类

DefaultAuthentication类的主要功能是判断当前上下文中的用户对象,开发人员根据此类提供的“Authenticate”事件,在其中判断用户对象是否存在,如果不存在,可根据需要自定义用户的身份验证对象,也可以设置为一般登陆用户。

学习的DefaultAuthenticaitonModule类,需要掌握两个概念:IIdentity和IPrincipal。其中IIdentify用来表示用户的验证标识,如用户名、验证类型等。IPrincipal用来表示用户对象的基本功能,其中包含IIdentify及用户的角色。DefaultAuthenticaitonModule类的最终目的,就是利用IIdentity和IPricipal实现自定义的用户对象。

语法定义:

public sealed class DefaultAuthenticationModule:IHttpModule

DefaultAuthenticaiton类的方法和属性都不重要,最重要的是其事件“Authenticate”,下面会尽心详细介绍。

 事件详解:

DefaultAuthenticationModule类只有一个事件“Authenticate”,此事件在对用户的请求进行身份验证后发生。在实际应用时,需要将事件添加到“Global”中,以保证全局的调用。Authenticate事件的默认语法如下:

public  void DefaultAuthentication_OnAuthenticate(object sender,DefaultAuthenticationEventArgs args)

其中包含参数“DefaultAuthenticationEventArgs”,用来提供“Context”属性,此时可以设置此属性的User为自定义的用户对象。如果只是设置为一般对象,可使用如下代码:

args.Context.User = new System.Security.Principal.GenericPrincipal(

  new System.Security.Principal.GenericIdentity("default"),new String[0]);

 

应用:让匿名登录用户显示登录信息

当用户匿名登录网站后,在网站中并没有存储用户的上下文信息,即上下文身份验证对象为空。但有时候用户希望自己未登录情况下的操作,可以在登录后继续操作(如未登录时在购物篮中添加了商品,登陆后这些商品还在自己的购物篮中)。此时就需要使用本例介绍的类:DefaultAuthenticationModuele.

using System;using System.Security;using System.Security.Principal;//定义用户对象的基本功能public class MyPrincipal : IPrincipal{    #region IPrincipal 成员    public IIdentity Identity    {        get { return new MyIdentity(); }    }    public bool IsInRole(string role)    {        return false;    }    #endregion}//定义用户对象的验证属性public class MyIdentity : IIdentity{    #region IIdentity 成员    public string AuthenticationType//验证类型    {        get { return "Forms"; }    }    public bool IsAuthenticated//是否已经通过验证    {        get { return true; }    }    public string Name//登录用户名    {        get { return "匿名用户"; }    }    #endregion}


在网站个目录下,添加一个“全局应用程序类”,默认名为“Global.asax”.在Global.asax的代码中,添加DefaultAutheticationModule类事件“Authenticate”,然后设置匿名用户登录的属性,代码如下:

  void DefaultAuthentication_OnAuthenticate(object sender,DefaultAuthenticationEventArgs args)   {       if (args.Context.User == null)//如果用户为匿名登录       {           args.Context.User = new MyPrincipal(); //重新定义用户对象       }    }


打开Default.aspx页面,在Page_Load事件中,将匿名用户的属性显示出来,代码如下:

  protected void Page_Load(object sender, EventArgs e)    {        Response.Write("当前用户的验证类型:" + HttpContext.Current.User.Identity.AuthenticationType + "<br />");        Response.Write("当前用户的姓名:" + HttpContext.Current.User.Identity.Name + "<br />");    }

打开Web.Config文件,修改窗体的验证类型,如下:

  <authentication mode="Forms"/>

运行程序,测试匿名用户对象的验证信息是否成功显示。

 

身份验证管理类:FormsAuthentication类

FormAuthentication类对应于身份验证的“Forms”模式,用来管理此模式下身份验证服务,如登录、注销等。

使用FormsAuthentication类可以将用户的登录信息,保存在Cookie中,还可以重定向用户请求的页,或者重定向登录页。使用FormsAuthenticaion类,可以防止匿名用户登录未被授权的页面。在实际应用中,需要结合Web.Config文件中的“authorzation”配置,后者用来配置用户的访问权限。

语法定义

public sealed class FormsAuthentication

从上述代码中,我们发现FormsAuthenticaiton是一个单独的类,未继承任何类,也未实现任何接口。

FormsAuthenticaiton只有一种构造方法,但通常不在应用程序中使用。所以FormsAuthenticaiton类的讲解,重点放在属性和方法上,使用这些方法和属性,不需要构造FormsAuthenticaition的实例。

属性详解:

DefaultURL:未指定重定向URL时,默认导航到的URL

LoginURL:默认登录页的URL

 

方法详解:

FormsAuthentication类的方法主要是进行重定向或票证操作等。

Authenticate:验证用户的姓名和密码

Decrypt :解密Forms身份验证票证

Encrypt:加密Forms身份验证票证

GetAuthCookie:指定用户创建身份验证Cookie

GetRedirectURL:返回原始请求的URL

RedirectFromLoginPage: 将经过身份验证的用户重定向回最初请求的 URL 或默认 URL。

RedirectToLoginPage:重定向到登录页

RenewTicketIfOld: 更新票证的发出日期和时间及过期日期的时间

SetAuthCookie:为指定的用户名创建一个身份验证票证,并将其添加到Cookie集合中

SignOut:注销当前用户的登录

 

下面代码演示如何使用FormsAuthentication类中的方法:

FormsAuthentication.Authenticate("管理员","123456"); //验证登录用户

FormsAuthentication.GetAuthCookie("管理员",true,null);  //创建身份验证Cookie

string myurl = FormsAuthentication.GetRedirectURL("管理员",true);  //返回原始请求的URL

FormsAuthenticatioin.RedirectFromLoginPage("管理员",true)://重定向到原始请求的URL

FormsAuthentication.SignOut(); //注销

 

应用:利用FormsAuthenticatioin类实现登录身份验证

FormsAuthentication类既然是用来管理验证用户的,那么本例就用其实现用户的登录和注销。本例要实现的功能是如果用户未登录,则不能访问Default.aspx页,正常登录后,可单击“注销”按钮,在返回到登录页面。

在Web.config中,配置登录验证属性,配置结果如下:

  <authentication mode="Forms">   <forms loginUrl="Login.aspx" defaultUrl="Default.aspx"     name="AuthSample" path="/" protection="All"></forms>  </authentication>  <authorization>   <deny users="?"/>  </authorization>

在网站的根目录下,添加一个登录页Login.aspx,添加两个TextBox用来输入用户名和密码,一个按钮用来执行登录操作:

双击“登录”按钮,书写登录要执行的验证和要重定向的URL,代码如下:

  protected void btnLogin_Click(object sender, EventArgs e)    {        //验证用户的登录-本例未使用数据库,此处直接使用用户名        //FormsAuthentication.Authenticate(txtName.Text,txtPass.Text)        if (txtName.Text == "admin" && txtPass.Text == "adminpass")        {//导航到用户原先的请求页面            FormsAuthentication.RedirectFromLoginPage("admin", true);        }    }

打开Default.aspx页,添加一个Label控件,用来显示用。在添加一个“注销”按钮,双击此按钮,在其Click事件中实现用户的注销操作,代码如下:

    protected void btnLogout_Click(object sender, EventArgs e)    {        FormsAuthentication.SignOut();//注销当前用户        FormsAuthentication.RedirectToLoginPage();//导航到登录页    }

在Page_Load事件中,书写显示登录用户的代码,如下:

    protected void Page_Load(object sender, EventArgs e)    {//显示当前登录用户名        Label1.Text = HttpContext.Current.User.Identity.Name;    }

将Default.aspx设置为起始页,运行,可以发现首先运行的其实是Login.aspx页,因为配置文件中设置了查看权限,用户只有登录后才可以查看Default.aspx。

输入登录信息:用户名admin,密码为adminpass。单击登录,此时系统自动导航到Default.aspx也,页面显示当前登录用户的姓名。

单击“注销”按钮,页面重新回到登录界面。



原创粉丝点击