javeweb 如何在使用SSL时始终将Cookie的secure属性设置为true设置 SameSite属性为lax
要在使用SSL时始终将Cookie的“secure”属性设置为“true”,以及设置SameSite属性为lax,可以通过以下步骤实现:
- 在web.xml文件中添加以下内容:
<session-config>
<cookie-config>
<secure>true</secure>
<http-only>true</http-only>
<same-site>lax</same-site>
</cookie-config>
</session-config>
- 如果使用Spring框架,则可以在WebSecurityConfigurerAdapter中配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf()
.disable()
.headers()
.httpStrictTransportSecurity()
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
.and()
.xssProtection()
.block(false)
.and()
.contentTypeOptions()
.disable()
.cacheControl()
.disable()
.and()
.addHeaderWriter(new StaticHeadersWriter("Set-Cookie", "HttpOnly;Secure;SameSite=Lax"))
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.apply(new JwtConfigurer(jwtTokenProvider));
}
- 如果使用Servlet,可以在Filter中设置:
public class CookieFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Lax");
chain.doFilter(request, response);
}
}
然后在web.xml文件中添加以下内容:
<filter>
<filter-name>cookieFilter</filter-name>
<filter-class>com.example.CookieFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cookieFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
``
原文地址: https://www.cveoy.top/t/topic/feAL 著作权归作者所有。请勿转载和采集!