以前用ASP,PHP,JSP编写网站代码的时候,站点安全性总是一件头疼的事情,虽然我们编写了用户登录,注册,验证页面,但是效果总是不理想。有时候我们不得不用大量的session变量来存放相关信息,处处设防。而在.NET环境下,这个问题处理起来就非常容易了。关键是要充分理解web.config文件。首先,介绍一下web.config文件。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<system.web>

<!-- 动态调试编译
设置 compilation debug="true" 以将调试符号(.pdb 信息)
插入到编译页中。因为这将创建执行起来
较慢的大文件,所以应该只在调试时将该值设置为 true,而所有其他时候都设置为
false。有关更多信息,请参考有关
调试 ASP.NET 文件的文档。
-->
<compilation defaultLanguage="vb" debug="true" />

<!-- 自定义错误信息
设置 customErrors mode="On" 或 "RemoteOnly" 以启用自定义错误信息,或设置为 "Off" 以禁用自定义错误信息。
为每个要处理的错误添加 <error> 标记。
-->
<customErrors mode="RemoteOnly" />

<!-- 身份验证
此节设置应用程序的身份验证策略。可能的模式是 \“Windows\”、
\“Forms\”、\“Passport\”和 \“None\”
-->
<authentication mode="Windows" />

<!-- 授权
此节设置应用程序的授权策略。可以允许或拒绝用户或角色访问
应用程序资源。通配符:"*" 表示任何人,"?" 表示匿名
(未授权的)用户。
-->
<authorization>
<allow users="*" /> <!-- 允许所有用户 -->

<!-- <allow users="[逗号分隔的用户列表]"
roles="[逗号分隔的角色列表]"/>
<deny users="[逗号分隔的用户列表]"
roles="[逗号分隔的角色列表]"/>
-->
</authorization>

<!-- 应用程序级别跟踪记录
应用程序级别跟踪在应用程序内为每一页启用跟踪日志输出。
设置 trace enabled="true" 以启用应用程序跟踪记录。如果 pageOutput="true",则
跟踪信息将显示在每一页的底部。否则,可以通过从 Web 应用程序
根浏览 "trace.axd" 页来查看
应用程序跟踪日志。
-->
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />

<!-- 会话状态设置
默认情况下,ASP.NET 使用 cookie 标识哪些请求属于特定的会话。
如果 cookie 不可用,则可以通过将会话标识符添加到 URL 来跟踪会话。
若要禁用 cookie,请设置 sessionState cookieless="true"。
-->
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false"
timeout="20"
/>

<!-- 全球化
此节设置应用程序的全球化设置。
-->
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />

</system.web>

</configuration>

好了,相信看过上面的介绍以后,对web.config文件一定非常了解了吧。下面我们就切入主题。为了防止用户没有经过验证就访问站点,我们的处理方法是当用户没有通过验证的时候点击任何页面将会直接跳到Login.aspx页面,具体代码如下:

<authentication mode="Forms">
<forms name="yourAuthCookie" loginUrl="login.aspx"
protection="All" path="/" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
但是这样会产生一个问题,那就是如果我的站点有一些信息是可以让任意用户随意访问的,比如站点简介,使用说明等。如果按照上面的处理方法岂不让用户觉得很麻烦,呵呵,不急,在ASP.NET中自然有相应的解决办法。下面的代码可以实现匿名用户访问Test.aspx页面:

<location path="test.aspx">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>

解决了上面两个问题,相信大家心里一定有底了吧。下面就开始实现login.aspx页面。利用C#和SQL Server2000,创建一个webform页面,加入相应的控件。具体代码如下:

<%@ Page language="c#" Codebehind="login.aspx.cs"
AutoEventWireup="false" Inherits="secure.login" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Secure Site</title>
<meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="javascript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="login" method="post" runat="server">
<table cellSpacing="0" cellPadding="0" border="0">
<tr>
<td vAlign="top" align="left">
<asp:label id="Message" Runat="server" ForeColor="#ff0000">
</asp:label>
</td>
</tr>
<tr>
<td vAlign="top" align="left">
<b>E-mail:</b>
</td>
</tr>
<tr>
<td vAlign="top" align="left">
<asp:textbox id="username" Runat="server" Width="120">
</asp:textbox>
</td>
</tr>
<tr>
<td vAlign="top" align="left">
<b>Password:</b>
</td>
</tr>
<tr>
<td vAlign="top" align="left">
<asp:textbox id="password" Runat="server"
Width="120" TextMode="Password">
</asp:textbox>
</td>
</tr>
<tr>
<td vAlign="top" align="left">
<asp:checkbox id="saveLogin" Runat="server"
Text="<b>Save my login</b>">
</asp:checkbox>
</td>
</tr>
<tr>
<td vAlign="top" align="right">
<asp:imagebutton id="btnLogin" Runat="server"
ImageUrl="/images/w2k/login/btnLogin.gif">
</asp:imagebutton>
</td>
</tr>
</table>
</form>
</body>
</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;
}
}

/// <summary>
/// Verifies the login and password that were given
/// </summary>
/// <param name="email">the login</param>
/// <param name="password">the password</param>
/// <param name="nLoginID">returns the login id</param>
/// <param name="nLoginType">returns the login type</param>
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;
}

/// <summary>
/// Access to our sql command
/// </summary>
protected SqlCommand Command
{
get { return sqlCommand; }
}

/// <summary>
/// Access to our data adapter
/// </summary>
protected SqlDataAdapter Adapter
{
get { return sqlDataAdapter; }
}

/// <summary>
/// Makes sure that everything is clear and ready for a new query
/// </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();
}

/// <summary>
/// Runs our command and returns the dataset
/// </summary>
/// <returns>the data set</returns>
protected DataSet RunQuery()
{
sqlDataAdapter.SelectCommand = Command;

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

sqlDataAdapter.Fill(sqlDataSet);

return sqlDataSet;
}
}
}

转载于:https://www.cnblogs.com/zzlifeng/archive/2007/11/28/975070.html

在ASP.NET中创建安全的web站点相关推荐

  1. 如何在ASP.NET中生成HTML5离线Web应用

    传统的Web应用程序有一个很大的症结是当用户的网络连接不好时,应用会加载失败,为了 解决这一问题,HTML5中引入了Web的离线工作的功能.离线功能使得Web应用程序类似于本机应用程序,当断开网络连接 ...

  2. 【转】asp.net中的WebApplication(web应用程序)和WebSite(网站)

    [转]asp.net中的WebApplication(web应用程序)和WebSite(网站) web application是MS在发布VS2005之后追加的SP1扩展包里的一种新的Web模式,We ...

  3. 【译】在ASP.NET中创建PDF-iTextSharp起步

    .Net framework 中自身并不包含可以和pdf打交道的方法.所以,当你需要你的ASP.Net Web应用程序中包含创建或与PDF文件交互的部分时,就不得不去找可用的第三方组件.使用谷歌可以搜 ...

  4. 在C++中创建并使用Web服务

    web服务的确是.net中让人激动的部分--但它们本身比.net要大.其中的道理很简单.几乎所有你能叫出名字的服务都有一些执行服务器端代码的机制:你在浏览器的地址栏中输入一个URL:接收到你的请求,服 ...

  5. ASP.NET Core Web Razor Pages系列教程:使用ASP.NET Core创建Razor Pages Web应用程序

    ASP .Net Core Razor Pages MySQL Tutorial 本系列教程翻译自微软官方教程,官方教程地址:Tutorial: Create a Razor Pages web ap ...

  6. 如何在ASP.NET中使用Windows Live Web Bar

    前言 Messenger Platform 团队将在 Mix 09 上推出新的 Windows Live Messenger Web Toolkit 和 Web Bar 控件,其中Web Bar控件包 ...

  7. 在ASP.NET中创建自定义控件初步(转)

    假如你有大量的asp.net页面,在其中你会要求访问者选择一个邮政编码.然后,基于这个邮编,显示与之相关的城市和省份.这项功能可以通过一个包含邮政编码的dropdownlist控件来组织,或者可以通过 ...

  8. asp.net中创建一个简单的自定义控件

    //程序名称:Class1.cs //程序功能:创建自定义控件 using System; using System.Collections.Generic; using System.Text; u ...

  9. 创建高性能移动 web 站点

    如果你的网站3秒钟没有响应,人们就会失去兴趣了.为了满足响应快这个愿望,需要一个不同的方法在手机上进行分析,设计和测试. 这篇文章将会对Johan Johansson在2013年4月提出" ...

  10. 创建高性能移动 web 站点【转载】

    如果你的网站3秒钟没有响应,人们就会失去兴趣了.为了满足响应快这个愿望,需要一个不同的方法在手机上进行分析,设计和测试. 这篇文章将会对Johan Johansson在2013年4月提出"  ...

最新文章

  1. JSP与Web技术概论
  2. CyberDuck:Macos和Linux服务器简洁传大文件
  3. 有关贝祖定理的一个小问题
  4. 【Android 应用开发】Android 开发错误集锦
  5. Redis 特殊数据类型 :Geospatial、Hyperloglog、Bitmap
  6. Mysql存储函数实现增删改查_使用存储过程操作数据库(实现增删改查)
  7. gdb 调试_GDB调试指南-源码查看
  8. php过程函数,php流程控制和函数
  9. 【Kafka】消息超过最大值限制max.request.size
  10. 认识下这位全能型漏洞猎人
  11. ESP8266 arduino下载程序不执行的若干bug
  12. shenyu2.5.0解决Exceeded limit on max bytes to buffer:262144
  13. 2018计算机考研国家线预测,2018考研国家线预测及解读-考研帮(kaoyan.com)
  14. 机架式服务器主要内部组件,戴尔R815机架式服务器
  15. Java判断邮箱格式是否正确
  16. CSS-设置表格样式
  17. 【信息检索导论】第一章 布尔检索
  18. EMV学习过程中问题解决及汇总
  19. 微软Azure组面试(部分)
  20. 【洛谷】入门2 分支结构

热门文章

  1. Unicode - 16 位统一超级字符集
  2. 音视频重新封装的流程
  3. 【bzoj1699/USACO2007】Balanced Lineup排队——RMQ问题
  4. 推荐几款好用的CRM
  5. JVM总结(一):概念----(无节操转载,潜心学习)
  6. 背景建模与前景检测之二(Background Generation And Foreground Detection Phase 2)
  7. .NET Framework中的配置文件(config)
  8. Docker 比较好的新入门教程
  9. 爬虫之User-Agent
  10. nginx编译安装和yum安装那个更好?