zoukankan      html  css  js  c++  java
  • 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();
            }
  • 相关阅读:
    MYSQL删除表的记录后如何使ID从1开始
    Python chardet 字符编码判断
    中文搜索引擎技术揭密
    python 处理中文网页时,忽略特殊字符,忽略异常
    cmd 之基础命令
    自己写的删除主键的存储过程
    朝花夕拾delphi的三层结构
    ERWIN中的一对多标识关系和一对多非标识关系
    翻页用的SQL
    关于 Ajax 的一篇通俗易懂的文章
  • 原文地址:https://www.cnblogs.com/ariklee/p/3670905.html
Copyright © 2011-2022 走看看