SpringBoot 动态设置响应头的content-type

需求: 当你想要即能返回application/json又能返回application/xml 的时候

基本上设置content-type通用的做法就是@requestMapping里的produces参数设置MediaType

根据这篇文章,我还以为已经没有办法动态设置content-type了,直到我在StackOverflow里看到了ResponseEntity

然后根据它官网上的api, 用以下方法解决了

@PostMapping(value = "/test")
    public ResponseEntity<Object> test() {

        HttpHeaders headers = new HttpHeaders();
        //根据自己的需要动态添加你想要的content type
        headers.add(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_VALUE);
        
        return new ResponseEntity<Object>("这里是你的响应体Object类和其子类都行",headers,HttpStatus.OK);
    }

另提一句, springboot也是能根据 @requestMapping里的consumes参数设置, 来区分调用哪个函数, 即便value是一样的

Spring Boot 项目中修复 `X-Content-Type-Options` HTTP 头缺失的安全漏洞,通常涉及配置 Web 安全性以确保响应头包含该字段。`X-Content-Type-Options` 是一种安全机制,用于防止浏览器 MIME 类型嗅探行为,从而减少某些类型的 XSS(跨站脚本攻击)风险。该头信息的值应设置为 `nosniff`。 ### 解决方案 #### 1. 配置 `X-Content-Type-Options` 响应头Spring Boot 应用中,可以通过自定义 `WebSecurityConfigurerAdapter` 或使用 `SecurityFilterChain` 来添加 HTTP 头。 以下是一个基于 `SecurityFilterChain` 的示例配置: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers(headers -> headers .contentSecurityPolicy(cps -> cps .policyDirectives("default-src 'self'; script-src 'self' https://trusted-cdn.com;") ) .and() .httpStrictTransportSecurity(hsts -> hsts .maxAgeInSeconds(31536000) .includeSubDomains(true) .preload(true) ) .and() .xssProtection(xss -> xss .block(true) ) .and() .frameOptions(frameOptions -> frameOptions .deny() ) .and() .contentTypeOptions(contentTypeOptions -> contentTypeOptions .block(false) // 设置 X-Content-Type-Options: nosniff ) ); return http.build(); } } ``` 上述代码通过 `.contentTypeOptions(contentTypeOptions -> contentTypeOptions.block(false))` 显式启用 `X-Content-Type-Options: nosniff` 响应头[^1]。 #### 2. 使用过滤器手动添加头信息 如果希望更细粒度地控制响应头,也可以通过实现 `OncePerRequestFilter` 并将其插入到 Spring Security 过滤链中: ```java import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; @Component public class CustomHeaderFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.setHeader("X-Content-Type-Options", "nosniff"); filterChain.doFilter(request, response); } } ``` 然后将此过滤器注册到 Spring Security 配置中: ```java @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.addFilterBefore(new CustomHeaderFilter(), SecurityPropertiesFilter.class); return http.build(); } ``` ### 验证方法 #### 1. 使用 Postman 或 curl 检查响应头 启动应用后,可以使用 `curl` 命令访问任意端点并检查返回头信息: ```bash curl -I http://localhost:8080/ ``` 期望看到如下输出: ``` HTTP/1.1 200 OK X-Content-Type-Options: nosniff ... ``` #### 2. 使用浏览器开发者工具检查响应头 打开 Chrome 开发者工具 (F12),切换到 **Network** 标签页,选择任意请求,在 **Headers** 部分查看是否存在 `X-Content-Type-Options: nosniff`。 #### 3. 使用 OWASP ZAP 或 Burp Suite 扫描 使用专业的安全测试工具(如 [OWASP ZAP](https://www.zaproxy.org/) 或 [Burp Suite](https://portswigger.net/burp))对应用进行扫描,验证是否仍报告 `X-Content-Type-Options` 缺失问题。 --- ### 相关加固建议 除了修复 `X-Content-Type-Options` 缺失问题外,还应同时考虑其他安全头信息的配置,例如: - `X-Frame-Options`:防止点击劫持攻击[^1] - `X-XSS-Protection`:启用浏览器内置的 XSS 过滤功能 - `Content-Security-Policy`:限制资源加载来源,防范 XSS 和数据注入攻击 - `Strict-Transport-Security`:强制 HTTPS 连接,增强传输安全性[^1] --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值