C#处理浏览器SameSite问题

WebHelper.cs修改如下两个方法,加入cookie.SameSite = SameSiteMode.Lax; cookie.Secure = false;两句代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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文件加入如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
<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的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

posted @   居无常  阅读(1610)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示