代码之家  ›  专栏  ›  技术社区  ›  davidalayachew

在Firefox上获取JSON时,CSP阻止了favicon.ico

  •  1
  • davidalayachew  · 技术社区  · 4 年前

    检查元件 “在Firefox上,我看到一个错误,原因是 Content Security Policy (CSP)

    Screenshot of the error message

    “内容安全策略:页面设置阻止加载位于的资源http://localhost:8081/favicon.ico (默认src)。”

    • 我试图通过application.properties禁用图标,但似乎没有任何效果。
    • 我创建了一个名为“favicon.ico”的图标,并将其放置在适当的目录中。令人恼火的是,这个页面仍然抛出了一个错误,同时我所有的其他页面都开始出现图标。
    • 我试过了 头的排列,包括将内容安全策略头设置为默认src self。虽然这可能是问题的根源,但没有一个有效,因为似乎有很多运动部件我没有完全掌握。
    • 我试图为“/favicon.ico”创建一个GET端点,但这似乎没有任何效果。
      • 此时,我已将图标添加到我的目录中,因此当我尝试点击端点时,它只向我发送了图标的图像,图标也显示在浏览器顶部的选项卡中,日志中没有错误。
    • 我试图搞乱WebSecurityConfigureAdapter,但很快就失控了,坦率地说,很多都没有意义。

    spring.mvc.favicon.enabled=false
    
    

    主文件-演示应用程序

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class DemoApplication {
    
       public static void main(String[] args) {
          System.getProperties().put( "server.port", 8081);
          SpringApplication.run(DemoApplication.class, args);
       }
    
    }
    

    Rest控制器=数据控制器

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class DataController
    {
    
       @GetMapping("/data")
       public Data data()
       {
       
          return new Data(123, "abc");
       
       }
      
    }
    

    返回类型=数据

    public class Data
    {
    
        private final long id;
        private final String data;
    
        public Data(long id, String data) { this.data = data; }
    
        public long getId() { return this.id; }
        public String getData() { return this.data; }
    
    }
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   davidalayachew    4 年前

    经过一些调试,我发现问题似乎是

    例如,如果我构建了一个只返回字符串的端点,Firefox将返回该字符串,图标将位于顶部的选项卡中。

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class DataController
    {
    
       @GetMapping("/data")
       public Data data()
       {
       
          return new Data(123, "abc");
       
       }
      
       @GetMapping("/abc123")
       public String abc123()
       {
       
          return "abc123";
       
       }
       
    }
    

    Screenshot of JSON response type with errors Screenshot of String response type with no errors

    然后我意识到——与其他浏览器不同,Firefox有一个内置的 JSON Viewer . 也就是说,如果整个页面都接收到数据 这纯粹是JSON ,那么Firefox将以完全不同的方式呈现页面。Firefox不会将简单的JSON字符串吐到页面上,而是使用一些奇特的UI来组织JSON,以便于阅读/解析。

    所以,作为最后的测试,我 turned off the JSON Viewer ,然后重新加载页面--所有操作都按预期进行。

    Screenshot of JSON response type with no errors

    我还要补充一点- 我真的不认为这是Firefox的一个bug --@granty指出, Mozilla themselves are looking into this . 这仅适用于以下端点: 整个响应都是JSON .

    如果您从整体上看,返回纯JSON的端点实际上只是数据流,而不是普通用户所使用的。那么你真的需要一个图标吗?哈哈,也许不是。

    推荐文章