zoukankan      html  css  js  c++  java
  • 网站用户登录认证

    cookie登录后同域名下的网站保持相同的登录状态。

    登录

    private void SetAuthCookie(string userId, bool createPersistentCookie)
    {
      var
    ticket = new FormsAuthenticationTicket(2, userId, DateTime.Now, DateTime.Now.AddDays(7), true, "", FormsAuthentication.FormsCookiePath);   string ticketEncrypted = FormsAuthentication.Encrypt(ticket);   HttpCookie cookie;   if (createPersistentCookie)//是否在设置的过期时间内一直有效   {     cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted)     {       HttpOnly = true,       Path = FormsAuthentication.FormsCookiePath,       Secure = FormsAuthentication.RequireSSL,       Expires = ticket.Expiration,       Domain = "cnblogs.com"//这里设置认证的域名,同域名下包括子域名如aa.cnblogs.com或bb.cnblogs.com都保持相同的登录状态     };   }   else   {     cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted)     {       HttpOnly = true,       Path = FormsAuthentication.FormsCookiePath,       Secure = FormsAuthentication.RequireSSL,       //Expires = ticket.Expiration,//无过期时间的,浏览器关闭后失效       Domain = "cnblogs.com"     };   }   HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);   HttpContext.Current.Response.Cookies.Add(cookie);
    }

    这样登录后,在同域名下的任何页面都可以得到用户状态

    判断用户是否登录

    public bool IsAuthenticated
    {
      get
      {
        bool isPass = System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
    
        if (!isPass)
          SignOut();
    
        return isPass;
      }
    }

    得到当前的用户名

    public string GetCurrentUserId()
    {
         return _httpContext.User.Identity.Name;
    }

    集群中每台web服务器的web.config需要设置相同的machineKey,这样只有同域名下 machineKey相同的服务器才能保持登录状态。

    <system.web>
    ...
    <machineKey validationKey="4A525ERTY83D72198CA34CD919C23F291BFF9E60223D94FDC8165E3EA3720619508A8B6695092F465AB15E0E57B3F472615DE46322B2A4A224ABDA369164DBFC" decryptionKey="646E17926C57B99B3645BB752016DCF7F79AC085E91DD54EB38A152127F20264" validation="SHA1" decryption="AES" />
    ...
    </system.web>
  • 相关阅读:
    图书管理系统登录界面
    图书管理系统的管理者界面
    图书管理系统-servlet层
    图书管理系统的dao层
    Linux 内核优化
    第十一章 Nginx之服务代理
    第十章 Nginx之LNMP拆分
    第九章 Nginx之LNMP架构
    第八章 Nginx常用模块
    第七章 WEB服务之Nginx
  • 原文地址:https://www.cnblogs.com/ggooo/p/4993366.html
Copyright © 2011-2022 走看看