我使用的是spring security,想在cookie加多个不同的属性,其中第一个属性设置httpOnly为true,第二个属性设置httpOnly为false
时间: 2024-02-18 18:00:04 浏览: 33
在 Spring Security 中,可以通过 `CookieSerializer` 接口来设置 Cookie 的多个属性,包括 `httpOnly` 属性。下面是一个示例代码,其中设置了两个不同的 Cookie 属性:
```java
@Configuration
@EnableWebSecurity
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 省略其他配置
.and()
.headers()
.httpStrictTransportSecurity()
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
.and()
.contentSecurityPolicy("default-src 'self'")
.and()
.csrf()
.csrfTokenRepository(csrfTokenRepository()) // 配置 CSRF token 的 Cookie 属性
.and()
.addFilterAfter(new CustomFilter(), CsrfFilter.class);
}
private CsrfTokenRepository csrfTokenRepository() {
CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse(); // 创建 CookieCsrfTokenRepository 对象
repository.setCookieMaxAge(3600); // 设置 Cookie 的过期时间
repository.setCookieName("XSRF-TOKEN"); // 设置 Cookie 的名称
repository.setCookiePath("/"); // 设置 Cookie 的路径
repository.setCookieHttpOnly(true); // 将 Cookie 的 httpOnly 属性设置为 true
return repository;
}
}
```
以上代码中,我们通过 `CsrfTokenRepository` 接口的实现类 `CookieCsrfTokenRepository` 来管理 CSRF token,然后通过调用 `CookieCsrfTokenRepository` 的方法来设置 CSRF token 的多个属性,包括 `httpOnly` 属性。需要注意的是,`httpOnly` 属性只能在 Cookie 创建时设置,无法修改,因此需要在创建 Cookie 时就决定该属性的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)