您当前的位置:首页 > 网站建设 > 网站维护
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

Nginx设置HttpOnly Secure SameSite参数解决Cookie信息丢失

51自学网 2025-02-05 12:16:41
  网站维护

一、背景说明

项目中使用了Nginx作为反向代理来访问系统,在漏洞扫描的过程中发现Cookie缺少 SameSite 属性。我们需要将SameSite属性设置为Strict或者 Lax。

二、Cookie安全相关属性

HttpOnly :

  • 在Cookie中设置了“HttpOnly”属性,通过程序(JS脚本、Applet等)将无法读取到Cookie信息。
  • 将HttpOnly 设置为true 防止程序获取cookie后进行攻击。

Secure :

  • 安全性,指定Cookie是否只能通过https协议访问,一般的Cookie使用HTTP协议既可访问。
  •  设置了Secure (没有值),则只有当使用https协议连接时cookie才可以被页面访问。可用于防止信息在传递的过程中被监听捕获后信息泄漏。

SameSite:

Chrome浏览器在51版本后为 Cookie 新增的属性,用来防止 CSRF 攻击和用户追踪。可以设置三个值:Strict、 Lax、 None

  • Strict:完全禁止第三方 Cookie,跨站点时,任何情况下都不会发送 Cookie。换言之,只有当前网页的 URL 与请求目标一致,才会带上 Cookie。Set-Cookie: CookieName=CookieValue; SameSite=Strict;
  • Lax:规则稍稍放宽,大多数情况也是不发送第三方 Cookie,但是导航到目标网址的 Get 请求除外。Set-Cookie: CookieName=CookieValue; SameSite=Lax;设置了Strict或Lax以后,基本就杜绝了 CSRF 攻击。当然,前提是用户浏览器支持 SameSite 属性。
  • None:Chrome 计划将Lax变为默认设置。这时,网站可以选择显式关闭SameSite属性,将其设为None。不过,前提是必须同时设置Secure属性(Cookie 只能通过 HTTPS 协议发送),否则无效。Set-Cookie: key=value; SameSite=None; Secure

浏览器F12 在网络下查看当前状态,SameSite属性缺失,我们需要通过配置nginx将SameSite属性设置为Strict或者 Lax。

三、配置路径

在nginx.conf 的 location 节点下进行配置

add_header Set-Cookie 'Path=/;httponly; Secure; SameSite=Lax';

下面是完整的 location 节点配置

server {		listen 443 ssl;		server_name test.app.com;		root html;		index index.html index.htm;				ssl_certificate C:/nginx/cert/client.pem;		ssl_certificate_key C:/nginx/cert/private.key;				ssl_session_timeout 4h;		# Enable SSL cache to speed up		ssl_session_cache shared:SSL:10m;				# intermediate configuration		ssl_protocols TLSv1.2 TLSv1.3;		ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305;		ssl_prefer_server_ciphers off;				client_max_body_size 100m;		proxy_http_version  1.1;				proxy_set_header  X-Real-IP  $remote_addr;		proxy_set_header Host $host;		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;			# HTTP Force Jump to HTTPS		proxy_redirect http:// $scheme://;		# To resolve nginx 504 issue		proxy_connect_timeout 1800s;		proxy_send_timeout 1800s;		proxy_read_timeout 1800s;				client_body_timeout 1800s;				# Nginx status		location /nginxstatus {			stub_status on;			access_log logs/nginx-status-$logdate.log;			auth_basic "NginxStatus"; 		}					# Application		location /api{            # 设置HttpOnly Secure SameSite参数解决Cookie跨域丢失			add_header Set-Cookie 'Path=/;httponly; Secure; SameSite=Lax';			proxy_pass http://127.0.0.1:8080;					}		}

修改后的情况


下载地址:
Nginx
宿主机无法访问docker容器中nginx服务的问题解决
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。