mvc4 Forms验证存储 两种登录代码

自己也不知道网上看到的第一种居多,第二种用到的人很少,第二种代码十分简洁,就是不清楚是否有安全隐患。

要采用Forms身份验证,先要在应用程序根目录中的Web.config中做相应的设置:

<authentication mode="forms"> <forms name=".ASPXAUTH " loginUrl="/Account/Login" /> </authentication>

1.第一种登录代码

 public ActionResult LoginIn(string username,string password) 
    { string userdata = username + "|" + password;
      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, 
        username, 
        DateTime.Now, 
        DateTime.Now.AddHours(1), true, 
        userdata); string encryptedTicket = FormsAuthentication.Encrypt(ticket);
      HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
      Response.Cookies.Add(authCookie); return RedirectToAction("Index");
    }

判断是否登录,取cookie里的登录信息。

public ActionResult Index()
    { if (User.Identity.IsAuthenticated)
      { string cookieName = FormsAuthentication.FormsCookieName; 
        HttpCookie authCookie = Request.Cookies[cookieName]; 
        FormsAuthenticationTicket authTicket = null; 
        authTicket = FormsAuthentication.Decrypt(authCookie.Value); string userinfo = authTicket.UserData;
      } return View();
    }

注销登录,这个两种方法通用。

public string loginOut() 
        {
            FormsAuthentication.SignOut(); return "ok";
        }

接下来是自己用的第二种登录代码

2.第二种登录代码

public ActionResult LoginIn(string username, string password)
        { string userdata = username + "|" + password;
            FormsAuthentication.SetAuthCookie(userdata,true); return RedirectToAction("Index");
        }

判断是否登录,取cookie里的登录信息。

public ActionResult Index()
    { if (User.Identity.IsAuthenticated)
      { string userinfo = User.Identity.Name;
      } return View();
    }