前言:
因为自己一直从事企业内部系统开发,一直将登陆用户信息保存在Session中.没有用过什么Forms身份验证,最近研究了一下这方面的东西,贴一下,欢迎大家拍砖.
Froms身份验证:
第一种:
string userName = "admin";
string pwd = "admin";
//第一种:授权并且完成跳转
//Web.config配置:
//<authentication mode="Forms">
// <forms loginUrl="~/Account/Login.aspx" defaultUrl="Default.aspx" timeout="2880" />
//</authentication>
if (userName == "admin" && pwd == "admin")
{
//如果验证通过,则重定向到原始请求URL或者defaultUrl.
//原始请求URL用ReturnUrl标识,如Default.aspx?ReturnUrl=test.aspx
//如果没有原始请求URL,则定向到defaultURL
FormsAuthentication.RedirectFromLoginPage(userName, false);
}
else
{
//定向到登陆页,即loginUrl.
FormsAuthentication.RedirectToLoginPage();
}
可以用HttpContext.Current.User.Identity.Name取出授权的用户名.
但是这种方式存在一个问题,授权用户名是保存在客户端Cookie中的,如果客户端禁用Cookie,那么授权用户名服务器就解密不到了.
Forms身份验证有一种办法就是将授权用户信息保存到URL中,只需配置Cookiless为UseUri就可以了:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" defaultUrl="Default.aspx" timeout="2880" cookieless="UseUri" />
</authentication>
授权之后URL变以:http://localhost:27130/(F(7QOqmTvEj....EwMB0))/Default.aspx
但是这样还是存在一个问题,用URL保存授权用户信息是在假设客户浏览器禁用了Cookie而采用的一种方式,但是有的客户浏览器如果没有禁用Cookie,它的URL会变得异常 繁琐.
第二种:
string userName = "admin";
string pwd = "admin";
if (userName == "admin" && pwd == "admin")
{
//自定义授权
//创建Forms身份验证票
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, false, 300);
//根据Forms身份验证票生成一个加密的客户端身份Cookie值.
string cookieValue = FormsAuthentication.Encrypt(ticket);
//客户端Forms身份验证票名称
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie cookie = new HttpCookie(cookieName, cookieValue);
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));
}
可以看到这种方式自定义了一个Forms身份验证票,并把Cookie信息保存.