【问题标题】:Spring boot+spring security - how can I block CORS requests on application layer?Spring boot + spring security - 如何阻止应用层上的CORS请求?
【发布时间】:2021-02-10 17:32:09
【问题描述】:

我有一个带有 Spring Security 的 Spring Boot 应用程序。当来自不同主机的任何客户端从我的应用程序调用 API 方法时,他会看到异常:

Access to XMLHttpRequest at 'http://localhost:8080/test' from origin 'http://localhost:8088' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

但是我的控制器仍然接受请求。我想禁用它。我希望 Spring Security 拒绝这些请求。

我试过了:

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors().and()

还有这个:

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

我想我不了解全貌,我想了解:如何在应用层阻止 CORS 请求?因为默认情况下 - 应用程序处理请求,而只是浏览器阻止响应。

【问题讨论】:

    标签: spring-boot spring-security cors


    【解决方案1】:

    字面上的答案是检查对Origin 标头的请求,如果存在则拒绝它,但这并不能解决您的实际问题。

    攻击者仍然可以欺骗用户发出跨域请求,只是他们无法使用 Ajax。他们仍然可以(例如)向隐藏的 iframe 提交表单并发起相同类型的恶意请求。

    同源策略仅适用于防止攻击者通过第三方读取数据。它不能阻止他们提出请求。 (并且 CORS 只允许有选择地禁用同源策略)。

    如果您想防御请求中的负载,那么您需要针对CSRF attacks 实施适当的防御。

    通常这会将出现在上一页正文中的令牌与会话中的匹配数据进行匹配。同源策略可防止攻击者从上一页读取令牌。

    由于您使用的是 Spring,因此请使用其built-in CSRF defences

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 2019-12-26
      • 1970-01-01
      • 2021-06-20
      • 2021-09-03
      • 2019-07-16
      • 2021-08-17
      • 2016-08-26
      相关资源
      最近更新 更多