C#處理瀏覽器SameSite問題


WebHelper.cs修改如下兩個方法,加入cookie.SameSite = SameSiteMode.Lax; cookie.Secure = false;兩句代碼

        public static void WriteCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.SameSite = SameSiteMode.Lax;
            cookie.Secure = false;
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.SameSite = SameSiteMode.Lax;
            cookie.Secure = false;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

  

Web.config文件加入如下配置:

<system.web>
    <anonymousIdentification cookieRequireSSL="false" />
    <!-- No config attribute for SameSite -->
    <authentication>
        <forms cookieSameSite="Lax" requireSSL="false" />
    </authentication>
    <!-- No config attribute for SameSite -->
    <roleManager cookieRequireSSL="false" />
    <!-- No config attribute for Secure -->
    <sessionState mode="InProc" timeout="180" cookieSameSite="Lax"/>
    ...
  </system.web>

js退出登錄邏輯中加入清理cookie的方法

        var loginout = function () { // 安全退出
                        ...
                        clearCookieAll();
                        ...
        }
        // 清理全部cookie
        var clearCookieAll = function() {
            var keys = document.cookie.match(/[^ =;]+(?==)/g)
            if (keys) {
                for (var i = keys.length; i--;) {
                    document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString() // 清除當前域名下的,例如:m.ratingdog.cn
                    document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString() // 清除當前域名下的,例如 .m.ratingdog.cn
                    document.cookie = keys[i] + '=0;path=/;domain=ratingdog.cn;expires=' + new Date(0).toUTCString() // 清除一級域名下的或指定的,例如 .ratingdog.cn
                }
            }
        }

  

參考鏈接:
https://www.cnblogs.com/wxx/p/12590007.html
https://docs.microsoft.com/en-us/aspnet/samesite/system-web-samesite


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM