asp.net网站中,我最常用的就是Form认证了,在实现登陆时,利用Form认证实现用户的访问权限,哪些页面是可以匿名登陆,哪些页面需要认证后才能访问,哪些页面不能访问等等权限。我还可在登陆时,使用FormsAuthenticationTicket 来记住登陆信息来实现网站记住当前登陆者的信息。

1:authentication节点

  在新建的asp.net网站,在web.config文件中,我们可以找到authentication节点

<!--修改验证模式为Forms-->
 <authentication mode="Forms">
 <forms loginUrl="~/Login.aspx" name="HotelUser" defaultUrl="Default.aspx"></forms>
</authentication>
 <!--禁止匿名登陆-->
<authorization>
 <deny users="?"/>
</authorization>

在authorization节点中“allow”表示允许,“*”表示所有用户,‘“deny”表示拒绝的意思,“?”表示匿名用户,这里表示根目录下所有的文件和所有的子目录都不能匿名访问,Login.aspx除外。

2:在web.config中,Location节点的使用。

  假如我们在MVC中添加一个Area(Admin)来实现网站后台登陆,我们也可以在这个web.config来实现“Admin”后台登陆的控制。

<location path="admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>

web.config的设置将作用于所在目录的所有文件及其子目录下的文件。通过loaction节点的path属性指定admin域页面。它表达的意思是拒绝所有用户登陆,除了角色是"admin"的用户。我们还可以使用location节点指向某个具体的页面。

<location path="Register.aspx">
  <system.web>
     <authorization>
       <allow users="*"/>
     </authorization>
  </system.web>
</location>

3:Forms验证机制;

  Forms验证在内部的机制是,把用户数据加密后保存在一个基于cookie的票据FormsAuthenticationTicket中,通过RedirectFromLoginPage方法或者SetAuthCookie方法实现了ticket和Cookie的设置,也就是设置了context.User的值,Cookie的属性是在Web.config的<forms name=".ASPXAUTH" loginUrl="Login.aspx" protection="All" path="/" timeout="20"/>中设置的,因为是经过特殊加密的,所以是比较安全的。

.net还留了用用户自定义的方法,可以吧Userdata信息传入到Ticket中,当我们需要这些信息时,可以通过Ticket的UserData属性得到。

if (this.TextBox1.Text == "Admin" && this.TextBox2.Text == "123456")
        {
            // 加密UserInfo
            UserInfo user = new UserInfo();
            user.Id = 1;
            user.Name = this.TextBox1.Text;
            user.Password = this.TextBox2.Text;
            user.RealName = "系统管理员";
            user.Roles = "Administrators,Users";
            string strUser = Serialize.Encrypt<UserInfo>(user);

// 设置Ticket信息
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1, user.Name, DateTime.Now, DateTime.Now.AddMinutes(20), false, strUser);

// 加密验证票据
            string strTicket = FormsAuthentication.Encrypt(ticket);

// 使用新userdata保存cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket);
            cookie.Expires = ticket.Expiration;
            this.Response.Cookies.Add(cookie);

this.Response.Redirect("Default.aspx");
        }

UserInfo是我们自定义的登陆者信息的类

[Serializable]
public class UserInfo
{
    //用户登录信息
    private int _nId;
    private string _sRealName;
    private string _sName;    
    private string _sPassword;
    private string _sRoles;

public int Id
    {
        get { return this._nId; }
        set { this._nId = value; }
    }
    public string RealName
    {
        get { return this._sRealName; }
        set { this._sRealName = value; }
    }
    public string Name
    {
        get { return this._sName; }
        set { this._sName = value; }
    }
    public string Password
    {
        get { return this._sPassword; }
        set { this._sPassword = value; }
    }
    public string Roles
    {
        get { return this._sRoles; }
        set { this._sRoles = value; }
    }

public UserInfo()
    {        
    }
}

记得要在此类加上系列化的标记。我们手动设置了一个UserInfo的对象,string strUser = Serialize.Encrypt<UserInfo>(user) 是将对象序列化成字符串的一个方法。

string strTicket = FormsAuthentication.Encrypt(ticket)将票据加密成字符串,最后HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket) 生成Cookie;FormsAuthentication.FormsCookieName获取的就是Web.config中配置的Cookie名称,也就是默认验证时产生的Cookie;

获取登陆信息时,我们可以在AppCode中创建一个页面基类,LoginBasePage;

public class LoginBasePage : Page
{
    protected UserInfo LoginUser
    {
        get
        {
            string strUser = ((FormsIdentity)this.Context.User.Identity).Ticket.UserData;

return Serialize.Decrypt<UserInfo>(strUser);               
        }
    }

public LoginBasePage()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
}

其他页面继承与这个类,就可以拿到LoginUser的信息了。

4:实现不同角色的权限控制;

  <configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <authorization>
            <allow roles="Users"></allow>
            <deny users="*"></deny>
        </authorization>
    </system.web>
</configuration>

表示允许角色为Users的用户可以访问,我们在登陆时user.Roles = "Administrators,Users"表示admin具有两种角色。

Forms基于角色的验证的内部机制是,将角色的属性也设置到了Context.User中,这里也需要手工代码处理一下。        

  首先,为了支持基于角色的验证,我们每进入一个页面都需要将角色信息设置到Context.User中,那么最好的办法就是在Global.asax 文件中的Application_AuthenticateRequest方法中设置。

  Application_AuthenticateRequest方法,是在每次验证请求时触发,它与另外一个方法Application_BeginRequest的区别就在于,Application_AuthenticateRequest方法内,能够访问Context.User.Identity,而Application_BeginRequest则无法访问。

  我们在根目录添加一个Global.asax 文件,增加如下代码:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        if (this.Context.User != null)
        {
            if (this.Context.User.Identity.IsAuthenticated)
            {
                if (this.Context.User.Identity is FormsIdentity)
                {
                    string strUser = ((FormsIdentity)this.Context.User.Identity).Ticket.UserData;

string[] roles = Serialize.Decrypt<UserInfo>(strUser).Roles.Split(',');

this.Context.User = new GenericPrincipal(this.Context.User.Identity, roles);
                }
            }
        }
    }

附加:本笔记只为自己学习使用,参照了http://www.cnblogs.com/Showshare/archive/2010/07/09/1772886.html这篇文章。

Asp.net Form登陆认证的回顾学习的更多相关文章

  1. asp.net form身份认证不定时认证失败的问题 排查

    1.网站出现form认证不定时认证失败.登陆过后 每隔一会儿就需要重新登陆.首先检查的是form身份认证票据设置的时间(正常) 然后检查加密后的身份认证信息写入的cookie的失效时间(正常) 2.这 ...

  2. 【转】权限管理学习 一、ASP.NET Forms身份认证

    [转]权限管理学习 一.ASP.NET Forms身份认证 说明:本文示例使用的VS2017和MVC5. 系统无论大小.牛逼或屌丝,一般都离不开注册.登录.那么接下来我们就来分析下用户身份认证. 简单 ...

  3. asp.net Form 认证【转】

    第一部分 如何运用 Form 表单认证 一.        新建一个测试项目 为了更好说明,有必要新建一个测试项目(暂且为“FormTest”吧),包含三张页面足矣(Default.aspx.Logi ...

  4. Django学习---Form组件认证

    Form组件认证 能够帮助我们做用户认证. 以前写我们自己写用户认证的时候,我们自己写HTML的form表单,点击提交,数据就被发送到后台,后台进行验证.在验证过程中我们就需要自己去写正则表达式去匹配 ...

  5. 简单的ASP.NET Forms身份认证

    读了几篇牛人的此方面的文章,自己也动手做了一下,就想有必要总结一下.当然我的文章质量自然不能与人家相比,只是写给从没有接触过这个知识点的朋友. 网站的身份认证我以前只知道session,偶然发现一些牛 ...

  6. 【翻译】asp.net core2.1认证和授权解密

    asp.net core2.1认证和授权解密 本篇文章翻译自:https://digitalmccullough.com/posts/aspnetcore-auth-system-demystifie ...

  7. {Django基础九之中间件} 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证

    Django基础九之中间件 本节目录 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证 六 xxx 七 xxx 八 xxx 一 前戏 我们在前面的课程中已经学会了 ...

  8. asp.net form 验证方式的使用(转载)

    如何运用 Form 表单认证 ASP.NET 的安全认证,共有“Windows”“Form”“Passport”“None”四种验证模式.“Windows”与“None”没有起到保护的作用,不推荐使用 ...

  9. 《ASP.NET4从入门到精通》学习笔记2

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/dongdongdongJL/article/details/37610807   <ASP.N ...

随机推荐

  1. 硬盘安装ubuntu120.04分区方案

    320G分区方案1/boot :256MB ext2swap :4G/ :40G ext4/tmp :5G ext4/var :20G ext4/usr :20G ext4/home :230GMB ...

  2. Oracle教程:如何诊断节点重启问题(转载)

    本文对如何诊断RAC环境中节点重启问题进行了介绍.适用于10gR2和11gR1. 首先我们对能够导致节点重启的CRS进程进行介绍.1.ocssd : 它的主要功能是节点监控(Node Monitori ...

  3. 为什么要使用Spark?

    现有的hadoop生态系统中存在的问题 1)使用mapreduce进行批量离线分析: 2)使用hive进行历史数据的分析: 3)使用hbase进行实时数据的查询: 4)使用storm进行实时的流处理: ...

  4. HDU 4407 Sum 容斥原理

    Sum Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Problem Desc ...

  5. 【测试】使用hr用户下的employees和departments表写一条SQL语句,(MG连接)

    SQL> select * from employees d, departments t where d.department_id=t.department_id; rows selecte ...

  6. centos 6.5 samba简单配置

    1.安装samba yum -y install samba  (我的显示已经安装啦!) 2.编辑samba的配置文件 vi /etc/samba/smb.conf 用 testparm查看我配置后的 ...

  7. No.004 Median of Two Sorted Arrays

    4. Median of Two Sorted Arrays Total Accepted: 104147 Total Submissions: 539044 Difficulty: Hard The ...

  8. LAMP+LNMP视频教程

    你是否在LAMP或是LNMP源码编译的道路上走过弯路,失败过或者目前还没有顺利安装过呢?另外网上有网上有很多LAMP/LNMP的一键安装脚本,如果拿过来直接用还是要改脚本.本教程的内容就能帮助你解决手 ...

  9. jqmobi 子菜单 高亮效果

    在jqmobi 中经常用到一个 子菜单 单击某一个选项 希望能高亮:所以我是这样做的1.HTML的页面显示是这样的 <div class="order_subheader01" ...

  10. psutil

    tar -zxvf psutil-2.1.3.tar.gz cd psutil-2.1.3 python setup.py install 安装是出现报错 error: command 'gcc' f ...