Firefox请求Spring Boot JSON接口时CSP拦截favicon.ico报错如何解决
报错原因
spring.mvc.favicon.enabled配置在Spring Boot 2.4及更高版本中已经被官方移除,该配置完全不生效,浏览器访问接口时仍会默认发起/favicon.ico的资源请求。- 你的
/data接口返回的是纯JSON数据,没有对应HTML页面,Firefox会调用自带的内置JSON预览页渲染响应内容,该预览页默认配置的CSP规则限制了favicon资源的加载,即使服务端存在favicon资源也会被拦截,最终抛出该报错。 - 额外补充:你提供的
Data类存在代码bug,构造方法中未对id成员变量赋值,接口返回的id会固定为0,而非你预期的123。
可行解决方案
- 方案1:全局添加CSP响应头
创建Spring MVC配置类,给所有响应添加允许图片资源加载的CSP规则,从根源解决拦截问题:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerInterceptor() { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception { response.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data:;"); } }); } }
- 方案2:直接屏蔽favicon请求
新增接口处理/favicon.ico请求,返回204无内容状态码,浏览器收到该状态码后会停止favicon加载逻辑,不会触发CSP报错:
import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class FaviconController { @GetMapping("/favicon.ico") public void handleFavicon(HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } }
- 方案3(仅本地调试适用):禁用Firefox内置JSON预览
在Firefox地址栏输入about:config,搜索devtools.jsonview.enabled,将配置值改为false,浏览器将直接展示原始JSON文本,不会使用带CSP限制的预览页,也就不会触发报错。
内容的提问来源于stack exchange,提问作者davidalayachew
相关产品推荐
相关产品推荐

