以前用ASP,PHP,JSP编写网站代码的时候,站点安全性总是一件头疼的事情,虽然我们编写了用户登录,注册,验证页面,但是效果总是不理想。有时候我们不得不用大量的session变量来存放相关信息,处处设防。而在.NET环境下,这个问题处理起来就非常容易了。关键是要充分理解web.config文件。首先,介绍一下web.config文件。
1<configuration>
2<system.web>
3<!-- 动态调试编译
4设置 compilation debug="true" 以将调试符号(.pdb 信息)
5插入到编译页中。因为这将创建执行起来
6较慢的大文件,所以应该只在调试时将该值设置为 true,而所有其他时候都设置为
7false。有关更多信息,请参考有关
8调试 ASP.NET 文件的文档。
9\-->
10<compilation debug="true" defaultlanguage="vb"></compilation>
11<!-- 自定义错误信息
12设置 customErrors mode="On" 或 "RemoteOnly" 以启用自定义错误信息,或设置为 "Off" 以禁用自定义错误信息。
13为每个要处理的错误添加 <error> 标记。
14\-->
15<customerrors mode="RemoteOnly"></customerrors>
16<!-- 身份验证
17此节设置应用程序的身份验证策略。可能的模式是 \“Windows\”、
18\“Forms\”、\“Passport\”和 \“None\”
19\-->
20<authentication mode="Windows"></authentication>
21<!-- 授权
22此节设置应用程序的授权策略。可以允许或拒绝用户或角色访问
23应用程序资源。通配符:"*" 表示任何人,"?" 表示匿名
24(未授权的)用户。
25\-->
26<authorization>
27<allow users="*"></allow> <!-- 允许所有用户 -->
28<!-- <allow users="[逗号分隔的用户列表]"
29roles="[逗号分隔的角色列表]"/>
30<deny users="[逗号分隔的用户列表]"
31roles="[逗号分隔的角色列表]"/>
32\-->
33</authorization>
34<!-- 应用程序级别跟踪记录
35应用程序级别跟踪在应用程序内为每一页启用跟踪日志输出。
36设置 trace enabled="true" 以启用应用程序跟踪记录。如果 pageOutput="true",则
37跟踪信息将显示在每一页的底部。否则,可以通过从 Web 应用程序
38根浏览 "trace.axd" 页来查看
39应用程序跟踪日志。
40\-->
41<trace enabled="false" localonly="true" pageoutput="false" requestlimit="10" tracemode="SortByTime"></trace>
42<!-- 会话状态设置
43默认情况下,ASP.NET 使用 cookie 标识哪些请求属于特定的会话。
44如果 cookie 不可用,则可以通过将会话标识符添加到 URL 来跟踪会话。
45若要禁用 cookie,请设置 sessionState cookieless="true"。
46\-->
47<sessionstate cookieless="false" mode="InProc" sqlconnectionstring="data source=127.0.0.1;user id=sa;password=" stateconnectionstring="tcpip=127.0.0.1:42424" timeout="20"></sessionstate>
48<!-- 全球化
49此节设置应用程序的全球化设置。
50\-->
51<globalization requestencoding="utf-8" responseencoding="utf-8"></globalization>
52</system.web>
53</configuration>
好了,相信看过上面的介绍以后,对web.config文件一定非常了解了吧。下面我们就切入主题。为了防止用户没有经过验证就访问站点,我们的处理方法是当用户没有通过验证的时候点击任何页面将会直接跳到Login.aspx页面,具体代码如下:
1<authentication mode="Forms">
2<forms loginurl="login.aspx" name="yourAuthCookie" path="/" protection="All"></forms>
3</authentication>
1<authorization>
2<deny users="?"></deny>
3</authorization>
但是这样会产生一个问题,那就是如果我的站点有一些信息是可以让任意用户随意访问的,比如站点简介,使用说明等。如果按照上面的处理方法岂不让用户觉得很麻烦,呵呵,不急,在ASP.NET中自然有相应的解决办法。下面的代码可以实现匿名用户访问Test.aspx页面:
1<location path="test.aspx">
2<system.web>
3<authorization>
4<allow users="?"></allow>
5</authorization>
6</system.web>
7</location>
解决了上面两个问题,相信大家心里一定有底了吧。下面就开始实现login.aspx页面。利用C#和SQL Server2000,创建一个webform页面,加入相应的控件。具体代码如下:
1@ Page language="c#" Codebehind="login.aspx.cs"
2AutoEventWireup="false" Inherits="secure.login"
1<html>
2<head>
3<title>Secure Site</title>
4<meta content="Microsoft Visual Studio 7.0" 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 ms_positioning="GridLayout">
10<form id="login" method="post" runat="server">
11<table border="0" cellpadding="0" cellspacing="0">
12<tr>
13<td align="left" valign="top">
14<asp:label forecolor="#ff0000" id="Message" runat="server">
15</asp:label>
16</td>
17</tr>
18<tr>
19<td align="left" valign="top">
20<b>E-mail:</b>
21</td>
22</tr>
23<tr>
24<td align="left" valign="top">
25<asp:textbox id="username" runat="server" width="120">
26</asp:textbox>
27</td>
28</tr>
29<tr>
30<td align="left" valign="top">
31<b>Password:</b>
32</td>
33</tr>
34<tr>
35<td align="left" valign="top">
36<asp:textbox id="password" runat="server" textmode="Password" width="120">
37</asp:textbox>
38</td>
39</tr>
40<tr>
41<td align="left" valign="top">
42<asp:checkbox id="saveLogin" runat="server" text="<b>Save my login</b>">
43</asp:checkbox>
44</td>
45</tr>
46<tr>
47<td align="right" valign="top">
48<asp:imagebutton id="btnLogin" imageurl="/images/w2k/login/btnLogin.gif" runat="server">
49</asp:imagebutton>
50</td>
51</tr>
52</table>
53</form>
54</body>
55</html>
界面做好之后,就开始编写提交按钮事件,首先需要注册该事件,代码如下:
private void InitializeComponent()
{
this.btnLogin.Click += new System.Web.UI.ImageClickEventHandler(this.btnLogin_Click);
.
.
.
}
事件注册好之后,自然就是编写事件处理函数了:
private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
CCommonDB sql = new CCommonDB();
string redirect = "";
if((redirect = sql.AuthenticateUser(this.Session, this.Response,
username.Text, password.Text, saveLogin.Checked)) != string.Empty)
{
// Redirect the user
Response.Redirect(redirect);
}
else
{
Message.Text = "Login Failed!";
}
}
读者看完上面的代码之后一定想问CCommonDB是哪里来的东东,这是我编写的一个类,用来处理用户登录信息的,如果成功则把相关信息写入session、Cookie和SQL数据库,同时跳到default.aspx页面。具体如下:
CCommonDB.cs
namespace secure.Components
{
public class CCommonDB : CSql
{
public CCommonDB() : base() { }
public string AuthenticateUser(
System.Web.SessionState.HttpSessionState objSession, // Session Variable
System.Web.HttpResponse objResponse, // Response Variable
string email, // Login
string password, // Password
bool bPersist // Persist login
)
{
int nLoginID = 0;
int nLoginType = 0;
// Log the user in
Login(email, password, ref nLoginID, ref nLoginType);
if(nLoginID != 0) // Success
{
// Log the user in
System.Web.Security.FormsAuthentication.SetAuthCookie(nLoginID.ToString(), bPersist);
// Set the session varaibles
objSession["loginID"] = nLoginID.ToString();
objSession["loginType"] = nLoginType.ToString();
// Set cookie information incase they made it persistant
System.Web.HttpCookie wrapperCookie = new System.Web.HttpCookie("wrapper");
wrapperCookie.Value = objSession["wrapper"].ToString();
wrapperCookie.Expires = DateTime.Now.AddDays(30);
System.Web.HttpCookie lgnTypeCookie = new System.Web.HttpCookie("loginType");
lgnTypeCookie.Value = objSession["loginType"].ToString();
lgnTypeCookie.Expires = DateTime.Now.AddDays(30);
// Add the cookie to the response
objResponse.Cookies.Add(wrapperCookie);
objResponse.Cookies.Add(lgnTypeCookie);
return "/candidate/default.aspx";
}
case 1: // Admin Login
{
return "/admin/default.aspx";
}
case 2: // Reporting Login
{
return "/reports/default.aspx";
}
default:
{
return string.Empty;
}
}
}
else
{
return string.Empty;
}
}
///
1<summary>
2/// Verifies the login and password that were given
3/// </summary>
///
1<param name="email"/>
the login
///
1<param name="password"/>
the password
///
1<param name="nLoginID"/>
returns the login id
///
1<param name="nLoginType"/>
returns the login type
public void Login(string email, string password, ref int nLoginID, ref int nLoginType)
{
ResetSql();
DataSet ds = new DataSet();
// Set our parameters
SqlParameter paramLogin = new SqlParameter("@username", SqlDbType.VarChar, 100);
paramLogin.Value = email;
SqlParameter paramPassword = new SqlParameter("@password", SqlDbType.VarChar, 20);
paramPassword.Value = password;
Command.CommandType = CommandType.StoredProcedure;
Command.CommandText = "glbl_Login";
Command.Parameters.Add(paramLogin);
Command.Parameters.Add(paramPassword);
Adapter.TableMappings.Add("Table", "Login");
Adapter.SelectCommand = Command;
Adapter.Fill(ds);
if(ds.Tables.Count != 0)
{
DataRow row = ds.Tables[0].Rows[0];
// Get the login id and the login type
nLoginID = Convert.ToInt32(row["Login_ID"].ToString());
nLoginType = Convert.ToInt32(row["Login_Type"].ToString());
}
else
{
nLoginID = 0;
nLoginType = 0;
}
}
}
abstract public class CSql
{
private SqlConnection sqlConnection; // Connection string
private SqlCommand sqlCommand; // Command
private SqlDataAdapter sqlDataAdapter; // Data Adapter
private DataSet sqlDataSet; // Data Set
public CSql()
{
sqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
sqlCommand = new SqlCommand();
sqlDataAdapter = new SqlDataAdapter();
sqlDataSet = new DataSet();
sqlCommand.Connection = sqlConnection;
}
///
1<summary>
2/// Access to our sql command
3/// </summary>
protected SqlCommand Command
{
get { return sqlCommand; }
}
///
1<summary>
2/// Access to our data adapter
3/// </summary>
protected SqlDataAdapter Adapter
{
get { return sqlDataAdapter; }
}
///
1<summary>
2/// Makes sure that everything is clear and ready for a new query
3/// </summary>
protected void ResetSql()
{
if(sqlCommand != null)
{
sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
}
if(sqlDataAdapter != null)
sqlDataAdapter = new SqlDataAdapter();
if(sqlDataSet != null)
sqlDataSet = new DataSet();
}
///
1<summary>
2/// Runs our command and returns the dataset
3/// </summary>
///
1<returns>the data set</returns>
protected DataSet RunQuery()
{
sqlDataAdapter.SelectCommand = Command;
sqlConnection.Open();
sqlConnection.Close();
sqlDataAdapter.Fill(sqlDataSet);
return sqlDataSet;
}
}
}