ASP.NET Forms 身份验证

在开发过程中,我们需要做的事情包括:

1. 在 web.config 中设置 Forms 身份验证相关参数。
2. 创建登录页。

登录页中的操作包括:

1. 验证用户名和密码是否正确。
2. 创建身份验证票证对象。
3. 将身份验证票证对象加密成字符串,写入 Cookies。
4. 重定向到原始请求 URL。

1. 简单演示

web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Forms">
      <forms loginUrl="~/logon.aspx" name="MyAuthForm">
        <credentials passwordFormat="Clear">
          <user name="username" password="password"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</configuration>

logon.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  protected void Button1_Click(object sender, EventArgs e)
  {
    if (FormsAuthentication.Authenticate(this.txtUsername.Text, this.txtPassword.Text))
      FormsAuthentication.RedirectFromLoginPage(this.txtUsername.Text, true);
    else
      Response.Write("用户名或密码错误!");
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
 <title>登录页</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
    Username: <asp:TextBox ID="txtUsername" runat="server" Width="100px" Text="username"></asp:TextBox><br />
    Password: <asp:TextBox ID="txtPassword" runat="server" Width="100px" Text="password"></asp:TextBox><br />
    <asp:Button ID="Button1" runat="server" Text="Sign In" OnClick="Button1_Click" />
 </div>
 </form>
</body>
</html>

2. Forms 验证参数

如果只是某些子目录中的页面访问请求需要进行身份验证,那么可以修改一下根路径下的 web.config。

web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Forms">
      <forms loginUrl="~/logon.aspx" name="MyAuthForm">
        <credentials passwordFormat="Clear">
          <user name="username" password="password"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

然后在需要进行身份验证的子目录中创建一个新的 web.config。

<?xml version="1.0"?>
<configuration>
  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</configuration>

我们还可以在根路径下的 web.config 中指定相关参数来控制身份验证模式。

cookieless
  定义是否使用 Cookie 以及 Cookie 的行为。
  .UseCookies
    指定无论在什么设备上都始终使用 Cookie。
  .UseUri
    指定从不使用 Cookie。
  .AutoDetect
    如果设备配置文件支持 Cookie,则指定使用 Cookie;否则不使用 Cookie。
  .UseDeviceProfile
    如果浏览器支持 Cookie,则指定使用 Cookie;否则不使用 Cookie。
    对于支持 Cookie 的设备,不尝试通过探测来确定是否已启用 Cookie 支持。
 
defaultUrl
  定义在身份验证之后用于重定向的默认 URL。 默认值为 "default.aspx"。
  当我们直接打开登录页进行登录后,该属性就很重要了。

loginUrl
  指定如果找不到任何有效的身份验证 Cookie,将请求重定向到的用于登录的 URL。默认值为 login.aspx。
 
name
  指定要用于身份验证的 HTTP Cookie。如果正在一台服务器上运行多个应用程序并且每个应用程序都需要
  唯一的 Cookie,则必须在每个应用程序的 Web.config 文件中配置 Cookie 名称。默认值为 ".ASPXAUTH"。
 
path
  为应用程序发出的 Cookie 指定路径。
  默认值是斜杠 (/),这是因为大多数浏览器是区分大小写的,如果路径大小写不匹配,浏览器不会送回 Cookie。
 
timeout
  指定 Cookie 过期前逝去的时间(以整数分钟为单位)。持久性 Cookie 不超时。默认值为 "30"(30 分钟)。

更详细信息,请参考 MSDN 文档。
ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.NETDEVFX.v20.chs/dv_ASPNETgenref/html/8163b8b5-ea6c-46c8-b5a9-c4c3de31c0b3.htm

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Forms">
      <forms loginUrl="~/logon.aspx" name="MyForm" defaultUrl="index.aspx" timeout="10">
        <credentials passwordFormat="Clear">
          <user name="username" password="password"/>
        </credentials>
      </forms>
    </authentication>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

3. 验证方法

我们可以使用下面 4 种方法中的一种进行票证写入和重定向操作,其实前 3 种只不过是对第 4 种方法的封装而已。推荐使用 1、4。注意后三种方法不支持cookieless="UseUri"。

// 1. 使用缺省身份验证票证
FormsAuthentication.RedirectFromLoginPage("username", true);

// 2. 使用缺省身份验证票证
FormsAuthentication.SetAuthCookie("username", false);
Response.Redirect(FormsAuthentication.GetRedirectUrl("username", false));

// 3. 使用缺省身份验证票证
Response.Cookies.Add(FormsAuthentication.GetAuthCookie("username", false));
Response.Redirect(FormsAuthentication.GetRedirectUrl("username", false));

// 4. 使用自定义身份验证票证
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddMinutes(10), false, null);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)));
Response.Redirect(FormsAuthentication.GetRedirectUrl("username", false));

4. 自定义身份标识类型

MSDN 文档告诉我们,可以在 Global.asax 中通过 Authenticate 事件使用自定义 Principal、Identity 替代 GenericPrincipal、FormsIdentity。因为 Authenticate 事件在 AuthenticateRequest 事件期间引发,因此我们可以在其他模块之前创建用户身份标识对象(FormsAuthenticationEventArgs.User)。

ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.NETDEVFX.v20.chs/cpref12/html/T_System_Web_Security_FormsAuthenticationEventHandler.htm

class MyPrincipal : System.Security.Principal.IPrincipal
{
  // ...
}

class MyIdentity : System.Security.Principal.IIdentity
{
  // ...
}
  
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
{
  if (FormsAuthentication.CookiesSupported)
  {
    if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
    {
      try
      {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(
          Request.Cookies[FormsAuthentication.FormsCookieName].Value);
 
        args.User = new MyPrincipal(new MyIdentity (ticket), new string[0]);
      }
      catch (Exception e)
      {
        // Decrypt method failed.
      }
    }
  }
  else
  {
    throw new HttpException("Cookieless Forms Authentication is not " +
      "supported for this application.");
  }

}

当然,还有另外一种简便的方法。

if (!(HttpContext.Current.User is MyPrincipal))
{
  HttpContext.Current.User = new MyPrincipal(new MyIdentity(ticket), roles);
}

只不过,你要找一个合适的时机而已。

5. FormsAuthentication

Authenticate
对照存储在应用程序配置文件中的凭据来验证用户名和密码。该方法只能验证存储在 web.config 中的用户名和密码信息,大多数时候我们会用自己的验证方法替代它。

Decrypt
解密从 Cookie 中获取的加密字符串,创建 FormsAuthenticationTicket 对象。

Encrypt
加密 FormsAuthenticationTicket,返回加密后字符串。

GetRedirectUrl
返回导致重定向到登录页的原始请求 URL。GetRedirectUrl 方法返回查询字符串中使用 ReturnURL 变量名指定的 URL。例如,在 URL http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx 中,GetRedirectUrl 方法返回返回 caller.aspx。如果 ReturnURL 变量不存在,GetRedirectUrl 方法将返回 DefaultUrl 属性中的 URL。

RedirectFromLoginPage
将经过身份验证的用户重定向回最初请求的 URL 或 DefaultUrl 。

RedirectToLoginPage
将浏览器重定向到登录 URL。

RenewTicketIfOld
有条件地更新 FormsAuthenticationTicket 的发出日期和时间以及过期日期和时间。 注意该方法只是返回更新后的 FormsAuthenticationTicket 对象,并不会写入 Cookies。

GetAuthCookie
为给定的用户名创建身份验证 Cookie,并不添加到响应的 Cookie 集合或 URL。

SetAuthCookie
为提供的用户名创建一个身份验证票证,并将其添加到响应的 Cookie 集合或 URL。

SignOut
从浏览器删除 Forms 身份验证票证。

6. 票证自定义数据应用

使用自定义票证时,我们可以添加一个 userData 参数。善加利用这个参数还是能带了一些意想不到的好处的,诸如存储用户 VIP 等级编号,所拥有的权限/角色集合等。当然 Cookie 和 URL 参数长度有限,这个自定义数据不能太长。

ASP.NET Forms 身份验证的更多相关文章

  1. asp.net Forms身份验证详解

    在做网站的时候,都会用到用户登录的功能.对于一些敏感的资源,我们只希望被授权的用户才能够访问,这让然需要用户的身份验证.对于初学者,通常将用户登录信息存放在Session中,笔者在刚接触到asp.ne ...

  2. asp.net Forms身份验证

    Web.config中的配置<system.web><authentication mode="Forms"> <forms name="K ...

  3. 两系统用asp.net forms 身份验证方式实现跨域登录信息共享

    1.两个系统的 web.config 都配置为 forms 验证方式( system.web —> authentication 节点) 2.在两个系统的Web.config里配置相同的 sys ...

  4. ASP.NET Forms身份验证概述

    表单身份验证允许您使用自己的代码对用户进行身份验证,然后在cookie或页面URL中维护身份验证令牌.表单身份验证通过FormsAuthenticationModule类参与ASP.NET页面生命周期 ...

  5. 采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展

    原文:http://www.cnblogs.com/sanshi/archive/2012/06/22/2558476.html 若是持久Cookie,Cookie的有效期Expiration属性有当 ...

  6. 采用Asp.Net的Forms身份验证时,非持久Cookie的过期时间会自动扩展

    问题描述 之前没有使用Forms身份验证时,如果在登陆过程中把HttpOnly的Cookie过期时间设为半个小时,总会收到很多用户的抱怨,说登陆一会就过期了. 所以总是会把Cookie过期时间设的长一 ...

  7. Asp.Net MVC 身份验证-Forms

    Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...

  8. ASP.NET:Forms身份验证和基于Role的权限验证

    从Membership到SimpleMembership再到ASP.NET Identity,ASP.NET每一次更换身份验证的组件,都让我更失望.Membership的唯一作用就是你可以参考它的实现 ...

  9. asp.net的forms身份验证 单用户身份验证

    asp.net的forms身份验证  单用户身份验证 首先要配置Web.config文件 <system.web> <authentication mode="Forms& ...

随机推荐

  1. android基于口令加密快速搞懂(一)

    import java.util.Random; import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypt ...

  2. xml文件解析(解析以后在RootTableViewController输出)

    这是从美团弄得xml文件,地区和经纬度. 你点了地区以后 ,  就可以查看经纬度 ,因为笔者懒, 有现成的文本框 , 所有偷懒了. 下面是一些枯燥的代码了 . #import <UIKit/UI ...

  3. Java实现单链表的各种操作

    Java实现单链表的各种操作 主要内容:1.单链表的基本操作 2.删除重复数据 3.找到倒数第k个元素   4.实现链表的反转   5.从尾到头输出链表 6.找到中间节点 7.检测链表是否有环 8.在 ...

  4. Linux下安装 Posgresql 并设置基本参数

    在Linux下安装Postgresql有二进制格式安装和源码安装两种安装方式,这里用的是二进制格式安装.各个版本的Linux都内置了Postgresql,所以可直接通过命令行安装便可.本文用的是Cen ...

  5. spool命令

    最近工作中,需对数据进行比对.在此之前,则需将数据导出.想到以前用过的spool命令,实验一番,分享如下: 需建SQL执行脚本,内容如下: set feedback off   --关掉行数显示set ...

  6. Lua的string和string库总结

    Lua有7种数据类型,分别是nil.boolean.number.string.table.function.userdata.这里我总结一下Lua的string类型和string库,复习一下,以便加 ...

  7. [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  8. [LeetCode] Walls and Gates 墙和门

    You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstac ...

  9. [LeetCode] Swap Nodes in Pairs 成对交换节点

    Given a linked list, swap every two adjacent nodes and return its head. For example,Given 1->2-&g ...

  10. 侯捷老师C++大系之C++面向对象开发:(一)不带指针的类:Complex复数类的实现过程

    一.笔记1.C++编程简介 2.头文件与类的声明 防卫式声明#ifndef __COMPLEX__#define __COMPLEX__ …… #endif头文件的布局模板简介template< ...