ASP.NET 中的表单身份验证和授权






4.33/5 (50投票s)
2006 年 4 月 21 日
4分钟阅读

832872
本文将介绍如何使用 ASP.NET 表单身份验证来保护网站。
引言
由于安全信息是高效 Web 编程的关键,Web 应用程序程序员始终关注安全性问题。本文将介绍如何使用 ASP.NET 表单身份验证来保护您的网站。
本文假定读者已经熟悉 ASP.NET 编程。
关键词
- web.config:应用程序配置文件包含特定于应用程序的设置。此文件包含公共语言运行时读取的配置设置(例如,程序集绑定策略、远程对象等),以及应用程序可以读取的设置 [MSDN]。
- 授权:授权的目的是确定是否应授予某个身份对给定资源的请求的访问类型 [MSDN]。
- 身份验证:身份验证是通过检查用户的凭据并根据某个权威机构验证这些凭据来发现和验证主体的身份的过程。在身份验证过程中获得的信息可供您的代码直接使用。也就是说,一旦发现主体的身份,您就可以使用 .NET Framework 基于角色的安全机制来确定是否允许该主体访问您的代码 [MSDN]。
背景
我搜索了许多网站,希望能找到一个可以帮助我保护网站免受未经授权访问的代码。在阅读了 C# 书籍后,我发现了一些不错的代码,它们帮助我创建了这个简单的应用程序。希望它能作为基本架构。
ASP.NET 中有三种身份验证方式:
- 表单,
- Windows,以及
- Passport.
本文将重点介绍第一种方式。
表单身份验证是基于 Cookie 的,因为 ASP.NET 会在客户端计算机上放置一个 Cookie 以跟踪用户。如果用户请求一个安全页面但尚未登录,ASP.NET 会将其重定向到登录页面。一旦用户通过身份验证,他/她就可以访问所请求的页面。
使用代码
在 web.config 中,将身份验证模式更改为 Forms
,然后添加 loginUrl="your default page"
。
在此部分,您将设置系统的默认页面。默认页面是每当用户尝试访问安全页面时发生故障时系统将用户重定向到的页面。
<!-- AUTHENTICATION
This section sets the authentication policies
of the application. Possible modes are "Windows",
"Forms", "Passport" and "None"
"None" No authentication is performed.
"Windows" IIS performs authentication (Basic,
Digest, or Integrated Windows) according to
its settings for the application.
Anonymous access must be disabled in IIS.
"Forms" You provide a custom form (Web page)
for users to enter their credentials, and then
you authenticate them in your application.
A user credential token is stored in a cookie.
"Passport" Authentication is performed via
a centralized authentication service provided
by Microsoft that offers a single logon
and core profile services for member sites.
-->
<authentication mode="Forms">
<forms loginUrl="Login.aspx">
</forms>
</authentication>
web.config 的此部分决定了哪些用户将被授权访问或被拒绝访问网站。默认值 <deny users="?" />
表示拒绝任何尝试访问网站的匿名(未经身份验证)用户。但是,此值可以更改。例如,<deny users="john”, “smith”, “Ahmed” />
表示拒绝用户:john、smith 和 Ahmed 访问此网站 - 这是一个黑名单;或者您可以说 <deny users="*" /> <allow users="john”, “smith”, “Ahmed” />
,这意味着拒绝所有用户,除了 john、smith 和 Ahmed。
<!-- AUTHORIZATION
This section sets the authorization policies
of the application. You can allow or deny access
to application resources by user or role.
Wildcards: "*" mean everyone, "?" means anonymous
(unauthenticated) users.
-->
<authorization>
<deny users="?" /> <!-- Allow all users -->
<!-- <allow users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
<deny users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
-->
</authorization>
角色
在一些企业网站中,多个员工需要访问系统以执行特定任务。然而,每个员工都有特定的角色,需要根据其工作性质或安全级别执行特定的操作。例如,人力资源经理可能不允许查看销售部门的数据。
ASP.NET 提供了角色的概念,该概念为每个角色提供对特定页面的不同视图。
<location path="HRpages">
<system.web>
<authorization>
<allow roles="HR" />
<deny users="*" />
</authorization>
</system.web>
</location>
<location path="salesPages">
<system.web>
<authorization>
<allow roles="sales" />
<deny users="*" />
</authorization>
</system.web>
</location>
这里的 location
指的是包含某些特定角色的 .aspx 文件的文件夹名称。例如,<location path="HRpages">
意味着 HRpages 文件夹下的所有 .aspx 文件都受到保护。<allow roles="HR" /><deny users="*" />
表示拒绝除具有 HR 角色的用户以外的所有人访问 HRpages 下的页面。
Login.aspx.cs
本节将展示读取 login.aspx 中的用户名和密码,并根据用户的角色将其重定向到特定页面的代码。
private void Submit1_Click (object sender, System.EventArgs e)
{
if(this.TextBox_username.Text.Trim()== "HR_manager"
&& this.TextBox_password.Text.Trim() == "password")
{
// Success, create non-persistent authentication cookie.
FormsAuthentication.SetAuthCookie(
this.TextBox_username.Text.Trim(), flase);
FormsAuthenticationTicket ticket1 =
new FormsAuthenticationTicket(
1, // version
this.TextBox_username.Text.Trim(), // get username from the form
DateTime.Now, // issue time is now
DateTime.Now.AddMinutes(10), // expires in 10 minutes
false, // cookie is not persistent
"HR" // role assignment is stored
// in userData
);
HttpCookie cookie1 = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket1) );
Response.Cookies.Add(cookie1);
// 4. Do the redirect.
String returnUrl1;
// the login is successful
if (Request.QueryString["ReturnUrl"] == null)
{
returnUrl1 = "HRpages/HR_main.aspx";
}
//login not unsuccessful
else
{
returnUrl1 = Request.QueryString["ReturnUrl"];
}
Response.Redirect(returnUrl1);
}
}
ticket1
对象是 FormsAuthenticationTicket
类型,它提供了一种创建和读取表单身份验证 Cookie 值的方法。之前的代码将在检查用户的密码后,将用户 HR_manager
重定向。如果密码正确,它将创建一个 Cookie 来跟踪用户并加密此 Cookie 的内容。
FormsAuthenticationTicket
的构造函数之一接受以下参数:
version
- 版本号。name
- 与票证关联的用户名。issueDate
- Cookie 发行的时间。expiration
- Cookie 的过期日期。isPersistent
- 如果 Cookie 是持久的,则为true
;否则为false
。userData
- 要存储在 Cookie 中的用户定义数据 [MSDN]。