• 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();
            }
  • 相关阅读:
    CF961E Tufurama 主席树
    [BZOJ3638 && BZOJ3272]带修区间不相交最大K子段和(线段树模拟费用流)
    [BZOJ5294][BJOI2018]二进制(线段树)
    [BZOJ5293][BJOI2018]求和(倍增)
    [BZOJ5306][HAOI2018]染色(容斥+FFT)
    [BZOJ5303][HAOI2018]反色游戏(Tarjan)
    [CF1053C]Putting Boxes Together(线段树)
    整体二分
    JSOI2018R2题解
    LCT维护子树信息
  • 原文地址:https://www.cnblogs.com/ariklee/p/3670905.html
Copyright © 2020-2023  润新知