asp.net Forms Authentication

一、Forms Authentication

  • 概述
    • 相比于windows authentication,forms authentication不需要windows账号,可以面向internet应用程序
    • 通过表单提交的用户名和密码进行登录验证
    • 密码在网络中传播,不安全
    • 基于会话的cookies
    • IIS提供默认实现,即FormsAuthenticationModule
  • 认证过程
    • 客户端向服务端发起请求

    • 服务端返回302以及重定向地址

    • 客户端重定向到登录页面

    • 用户输入账号、密码后提交到服务器

    • 服务器验证成功后,返回302,重定向地址,并将认证票据FormsAuthenticationTicket加密保存到客户端cookie中

    • 客户端重定向到之前想要访问的资源,并自动携带认证cookie

    • 服务器在管道事件AuthenticateRequest中将cookie解密,从中提取认证票据FormsAuthenticationTicket,生成FormsIdentity,再生产GenericPrincipal,并将Principal设置到Thread.CurrentPrincipal以及HttpContext.Current.User

      • FormsAuthenticationTicket
        • 包含Name以及UserData
        • UserData可以保存除用户名之外的其他用户信息
      • FormsIdentity
        • 包含Name、AuthenticationType、FormsAuthenticationTicket
      • GenericPrincipal
        • 包含FormsIdentity

在这里插入图片描述

private void SetPrincipal(IPrincipal principal)
{
    Thread.CurrentPrincipal = principal;
    if (HttpContext.Current != null)
    {
        HttpContext.Current.User = principal;
    }
}
  • 开启forms authentication
    • 启用FormsAuthenticationModule
    • 给需要受保护的资源设置访问权限,例如,AuthorizeAttribute
<system.web>
    <authentication mode="Forms">
      <forms loginUrl="Login/Index"/>
    </authentication>
  </system.web>
  • LogIn
    • 账号密码校验通过后设置authentication的cookies
      • FormsAuthentication.GetAuthCookie()
        • 生成认证票据,并加密生成cookies
      • FormsAuthentication.SetAuthCookie()
        • 内部先调用GetAuthCookie()方法生成cookie
        • 再将cookie添加到响应中
      • FormsAuthentication.RedirectFromLoginPage()
        • 内部调用SetAuthCookie()
        • 再进行重定向
  • LogOut
    • FormsAuthentication.SignOut()
      • 从浏览器中移除窗体身份验证票证
  • Request.IsAuthenticated
    • 判断请求是否通过认证
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值