一、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
- FormsAuthenticationTicket
-
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()
- 再进行重定向
- FormsAuthentication.GetAuthCookie()
- 账号密码校验通过后设置authentication的cookies
- LogOut
- FormsAuthentication.SignOut()
- 从浏览器中移除窗体身份验证票证
- FormsAuthentication.SignOut()
- Request.IsAuthenticated
- 判断请求是否通过认证