使用HttpContext的User属性来实现用户验证

HttpContext 类包含了个别 HTTP 请求的所有特定 HTTP 信息。这个示例主要是讲如何使用 HttpContext 类中的 User 属性来实现用户验证!

用户验证是大部分 ASP.NET WEB 应用程序都要用到的,它在整个应用程序中占有很重要的地位,在 .NET 中,包含了很多种用户验证方式,如众所周知的 PassPort 认证, Windows 认证, Form 认证等等,可是这些都很难满足我们在实际应用中的需求,以致于很多朋友都是自己另外写代码来实现自己需要的功能,这让我们在安全性以及系统效率上要考虑很多。

实际上, ASP.NET 中内置的用户验证机制功能非常强大,同时也具有非常好的的可扩展性,它能够在 HttpContext 对象中生成一个名为 User 的属性,这个属性能让我们访问各种信息,包括用户是否已验证,用户的类型,用户名等等,我们还可以对该属性的功能进性扩展,以实现我们的要求。

分配给 HttpContext.User 的对象必须实现 IPrincipal 接口,而 Iprincipal 定义的属性之一是 Identity ,它必须实现 Iidentity 接口。因为,我们只要写了实现这两个接口的类,就可以在这些类中添加任何我们所需要的功能。

首先,我们创建两个实现 Iprincipal 和 Iidentity 的类,分另为 MyIprincipal 和 MyIdentity

MyIprincipal.cs

using System;

using System.Collections;

namespace HttpContextUserEG

{

///

1<summary>
2
3/// MyPrincipal  的摘要说明。 
4
5/// </summary>

/// 实现 IPrincipal 接口

public class MyPrincipal : System.Security.Principal.IPrincipal

{

private System.Security.Principal.IIdentity identity;

private ArrayList roleList;

public MyPrincipal(string userID,string password)

{

//

// TODO: 在此处添加构造函数逻辑

//

identity = new MyIdentity(userID,password);

if(identity.IsAuthenticated)

{

// 如果通过验证则获取该用户的 Role ,这里可以修改为从数据库中

// 读取指定用户的 Role 并将其添加到 Role 中,本例中直接为用户添加一个 Admin 角色

roleList = new ArrayList();

roleList.Add("Admin");

}

else

{

// do nothing

}

}

public ArrayList RoleList

{

get

{

return roleList;

}

}

#region IPrincipal 成员

public System.Security.Principal.IIdentity Identity

{

get

{

// TODO: 添加 MyPrincipal.Identity getter 实现

return identity;

}

set

{

identity = value;

}

}

public bool IsInRole(string role)

{

// TODO: 添加 MyPrincipal.IsInRole 实现

return roleList.Contains(role);;

}

#endregion

}

}

MyIdentity.cs

using System;

namespace HttpContextUserEG

{

///

1<summary>
2
3/// MyIdentity  的摘要说明。 
4
5/// </summary>

/// 实现 IIdentity 接口

public class MyIdentity : System.Security.Principal.IIdentity

{

private string userID;

private string password;

public MyIdentity(string currentUserID,string currentPassword)

{

//

// TODO: 在此处添加构造函数逻辑

//

userID = currentUserID;

password = currentPassword;

}

private bool CanPass()

{

// 这里朋友们可以根据自己的需要改为从数据库中验证用户名和密码,

// 这里为了方便我直接指定的字符串

if(userID == "yan0lovesha" && password == "iloveshasha")

{

return true;

}

else

{

return false;

}

}

public string Password

{

get

{

return password;

}

set

{

password = value;

}

}

#region IIdentity 成员

public bool IsAuthenticated

{

get

{

// TODO: 添加 MyIdentity.IsAuthenticated getter 实现

return CanPass();

}

}

public string Name

{

get

{

// TODO: 添加 MyIdentity.Name getter 实现

return userID;

}

}

// 这个属性我们可以根据自己的需要来灵活使用 , 在本例中没有用到它

public string AuthenticationType

{

get

{

// TODO: 添加 MyIdentity.AuthenticationType getter 实现

return null;

}

}

#endregion

}

}

在完成了这两个类之后我们还要创建一个自己的 Page 类 , 来配合我们的验证 , 这里我们将其命名为 MyPage, 继承自 Page 类

MyPage.cs

using System;

using System.Collections;

namespace HttpContextUserEG

{

///

1<summary>
2
3/// MyPage  的摘要说明。 
4
5/// </summary>

/// 继承自 Page 类

public class MyPage : System.Web.UI.Page

{

public MyPage()

{

//

// TODO: 在此处添加构造函数逻辑

//

}

protected override void OnInit(EventArgs e)

{

base.OnInit (e);

this.Load +=new EventHandler(MyPage_Load);

}

// 在页面加载的时候从缓存中提取用户信息

private void MyPage_Load(object sender, System.EventArgs e)

{

if(Context.User.Identity.IsAuthenticated)

{

if(Context.Cache["UserMessage"] != null)

{

Hashtable userMessage = (Hashtable)Context.Cache["UserMessage"];

MyPrincipal principal = new MyPrincipal(userMessage["UserID"].ToString(),userMessage["UserPassword"].ToString());

Context.User = principal;

}

}

}

}

}

下面就是我们的界面 WebForm.aspx 和 WebForm.aspx.cs

WebForm.aspx

1@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="HttpContextUserEG.WebForm1" 
 1<html>
 2<head>
 3<title>WebForm1</title>
 4<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"/>
 5<meta content="C#" name="CODE_LANGUAGE"/>
 6<meta content="JavaScript" name="vs_defaultClientScript"/>
 7<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"/>
 8</head>
 9<body>
10<form id="Form1" method="post" runat="server">
11<p><font face="  宋体  "> 用户名  : 
12
13<asp:textbox id="tbxUserID" runat="server"></asp:textbox><br/>
14
15密  码  : 
16
17<asp:textbox id="tbxPassword" runat="server" textmode="Password"></asp:textbox></font></p>
18<p><font face="  宋体  ">
19<asp:button id="btnLogin" runat="server" text="  登录  "></asp:button>
20<asp:label id="lblLoginMessage" runat="server"></asp:label></font></p>
21<p><font face="  宋体  ">
22<asp:panel id="Panel1" runat="server" visible="False">
23<p>
24<asp:button id="btnAdmin" runat="server" text="  角色  1"></asp:button>
25<asp:button id="btnUser" runat="server" text="  角色  2"></asp:button></p>
26<p>
27<asp:label id="lblRoleMessage" runat="server"></asp:label></p>
28</asp:panel>
29<p></p>
30</font>
31</p></form>
32</body>
33</html>

WebForm1.aspx.cs

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.Caching;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace HttpContextUserEG

{

///

1<summary>
2
3/// WebForm1  的摘要说明。 
4
5/// </summary>

/// 将这里本来继

Published At
Categories with Web编程
Tagged with
comments powered by Disqus