苏飞论坛

标题: asp.net通过FormsAuthentication实现用户登录和退出 [打印本页]

作者: 站长苏飞    时间: 2013-11-8 09:09
标题: asp.net通过FormsAuthentication实现用户登录和退出
     asp.net通过FormsAuthentication实现用户登录和退出

Web.config配置项描述:

[code=html]<authentication mode="Forms">
     <forms
         name=".ASPXAUTH"
         loginUrl="login.aspx"
         defaultUrl="default.aspx"
         protection="All"
         timeout="30"
         path="/"
         requireSSL="false"
         slidingExpiration="false"
         enableCrossAppRedirects="false"
         cookieless="UseDeviceProfile"
         domain=""
     />
</authentication>[/code]

  上面的属性都是默认的设置,也就是说,如果你的哪项配置属性与上述代码一致,就可以省略该属性例如<forms name="MyAppAuth" />。下面依次介绍一下各种属性:

name

——Cookie的名字。Forms Authentication可能会在验证后将用户凭证放在Cookie中,name属性决定了该Cookie的名字。通过FormsAuthentication.FormsCookieName属性可以得到该配置值(稍后介绍FromsAuthentication类)。

loginUrl

——登录页的URL。通过FormsAuthentication.LoginUrl属性可以得到该配置值。当调用FormsAuthentication.RedirectToLoginPage()方法时,客户端请求将被重定向到该属性所指定的页面。loginUrl的默认值为“login.aspx”,这表明即便不提供该属性值,ASP.NET也会尝试到站点根目录下寻找名为login.aspx的页面。

defaultUrl

——默认页的URL。通过FormsAuthentication.DefaultUrl属性得到该配置值。

protection

——Cookie的保护模式,可取值包括All(同时进行加密和数据验证)、Encryption(仅加密)、Validation(仅进行数据验证)和None。为了安全,该属性通常从不设置为None。

timeout

——Cookie的过期时间。

path

——Cookie的路径。可以通过FormsAuthentication.FormsCookiePath属性得到该配置值。

requireSSL

——在进行Forms Authentication时,与服务器交互是否要求使用SSL。可以通过FormsAuthentication.RequireSSL属性得到该配置值。

slidingExpiration

——是否启用“弹性过期时间”,如果该属性设置为false,从首次验证之后过timeout时间后Cookie即过期;如果该属性为true,则从上次请求该开始过timeout时间才过期,这意味着,在首次验证后,如果保证每timeout时间内至少发送一个请求,则Cookie将永远不会过期。通过FormsAuthentication.SlidingExpiration属性可以得到该配置值。

enableCrossAppRedirects

——是否可以将以进行了身份验证的用户重定向到其他应用程序中。通过FormsAuthentication.EnableCrossAppRedirects属性可以得到该配置值。为了安全考虑,通常总是将该属性设置为false。

cookieless

——定义是否使用Cookie以及Cookie的行为。Forms Authentication可以采用两种方式在会话中保存用户凭据信息,一种是使用Cookie,即将用户凭据记录到Cookie中,每次发送请求时浏览器都会将该Cookie提供给服务器。另一种方式是使用URI,即将用户凭据当作URL中额外的查询字符串传递给服务器。该属性有四种取值——UseCookies(无论何时都使用Cookie)、UseUri(从不使用Cookie,仅使用URI)、AutoDetect(检测设备和浏览器,只有当设备支持Cookie并且在浏览器中启用了Cookie时才使用Cookie)和UseDeviceProfile(只检测设备,只要设备支持Cookie不管浏览器是否支持,都是用Cookie)。通过FormsAuthentication.CookieMode属性可以得到该配置值。通过FormsAuthentication.CookiesSupported属性可以得到对于当前请求是否使用Cookie传递用户凭证。

domain

——Cookie的域。通过FormsAuthentication.CookieDomain属性可以得到该配置值。

登录有代码:

[code=csharp][HttpPost]
public ActionResult LogOn(LogOnModel model)
{
  if (ModelState.IsValid)
  {

    if (model.UserName == "username" && model.Password == "password")
    {
      FormsAuthentication.RedirectFromLoginPage(model.UserName, model.RememberMe);
    }
  }

  return View("logon failed!");
}[/code]

退出时的代码:

[code=csharp]public ActionResult LogOff()
{
      //FormsService.SignOut();
      FormsAuthentication.SignOut();
      return RedirectToAction("Index", "Home");
}[/code]







欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4