程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 在ASP.NET中創建安全的web站點

在ASP.NET中創建安全的web站點

編輯:.NET實例教程

以前用ASP,PHP,JSP編寫網站代碼的時候,站點安全性總是一件頭疼的事情,雖然我們編寫了用戶登錄,注冊,驗證頁面,但是效果總是不理想。有時候我們不得不用大量的session變量來存放相關信息,處處設防。而在.Net環境下,這個問題處理起來就非常容易了。關鍵是要充分理解web.config文件。首先,介紹一下web.config文件。




好了,相信看過上面的介紹以後,對web.config文件一定非常了解了吧。下面我們就切入主題。為了防止用戶沒有經過驗證就訪問站點,我們的處理方法是當用戶沒有通過驗證的時候點擊任何頁面將會直接跳到Login.ASPx頁面,具體代碼如下:


protection="All" path="/" />




但是這樣會產生一個問題,那就是如果我的站點有一些信息是可以讓任意用戶隨意訪問的,比如站點簡介,使用說明等。如果按照上面的處理方法豈不讓用戶覺得很麻煩,呵呵,不急,在ASP.Net中自然有相應的解決辦法。下面的代碼可以實現匿名用戶訪問Test.ASPx頁面:







解決了上面兩個問題,相信大家心裡一定有底了吧。下面就開始實現login.ASPx頁面。利用C#和SQL Server2000,創建一個webform頁面,加入相應的控件。具體代碼如下:

<%@ Page language="c#" Codebehind="login.aspx.cs"
AutoEventWireup="false" Inherits="secure.login" %>







name="vs_targetSchema">












E-mail:










PassWord:




Width="120" TextMode="PassWord">




" align="left">
Text="Save my login">





ImageUrl="/images/w2k/login/btnLogin.gif">







界面做好之後,就開始編寫提交按鈕事件,首先需要注冊該事件,代碼如下:

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

///


/// VerifIEs the login and passWord that were given
///

/// the login
/// the passWord
/// returns the login id
/// 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;
}

///


/// Access to our sql command
///

protected SqlCommand Command
{
get { return sqlCommand; }
}

///


/// Access to our data adapter
///

protected SqlDataAdapter Adapter
{
get { return sqlDataAdapter; }
}

///


/// Makes sure that everything is clear and ready for a new query
///

protected void ResetSql()
{
if(sqlCommand != null)
{
sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
}
if(sqlDataAdapter != null)
sqlDataAdapter = new SqlDataAdapter();

if(sqlDataSet != null)
sqlDataSet = new DataSet();
}

///


/// Runs our command and returns the dataset
///

/// the data set
protected DataSet RunQuery()
{
sqlDataAdapter.SelectCommand = Command;

sqlConnection.Open();
sqlConnection.Close();

sqlDataAdapter.Fill(sqlDataSet);

return sqlDataSet;
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved