【问题标题】:Spring-Security OAuth WebMVC Invalid CORS requestSpring-Security OAuth WebMVC 无效的 CORS 请求
【发布时间】:2016-04-11 04:17:57
【问题描述】:

希望我的最后一个问题能够让所有这些工作。使用 Spring Security OAuth 2.0.8 和 Spring-Web MVC 4.2.3 公开 OAuth 端点(系统的大部分使用 RESTEasy 作为 REST 端点,它有自己的 CORS 过滤器)。

我正在尝试使用 Web MVC 4.2.x 中现在提供的全局默认 CORS 支持。但是,当针对 /oauth/token 端点发出测试预检请求时,我总是收到 403 Invalid CORS Request 响应。 Fiddler 的示例请求如下。

OPTIONS http://localhost:8080/myapp/oauth/token HTTP/1.1
User-Agent: Fiddler
Host: localhost:8080
Origin: http://testfakeorigin.overtherainbow.com
Access-Control-Request-Method: POST

尽管这通过并被确定为正确的预检请求,但看起来该请求在第 81 行的 DefaultCorsProcessor 中失败,因为 CorsConfiguration 为空。即使我在我的 WebMvcConfigurerAdapter 中明确添加了 CORS 注册表映射(根据文档,这不应该是必需的),配置最终仍然为空。接下来我应该看哪里?

【问题讨论】:

标签: spring spring-mvc oauth spring-security cors


【解决方案1】:

您可以在 @Configuration 类中自定义整个应用程序的 CORS(跨源资源共享),这样您的所有控制器都会被自动覆盖。看看:

@Configuration
@EnableWebSecurity( debug = true )
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
     /* ... configurations */
     @Bean
     public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();
        config.addAllowedMethod(HttpMethod.POST);
        config.addAllowedMethod(HttpMethod.GET);
        config.addAllowedMethod(HttpMethod.PUT);
        config.addAllowedMethod(HttpMethod.DELETE);
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
     }
}

注意:您可以定义将在配置中应用的方法动词

最好的问候!

【讨论】:

    【解决方案2】:

    在实际的POST 之前,您可能会自动发出OPTIONS 请求。通过default,仅允许您在RequestMapping 中指定的方法。因此,您必须明确允许跨源请求使用 OPTIONS 方法。

    使用全局配置的一种方法如下:

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "OPTIONS").allowedOrigins("http://testfakeorigin.overtherainbow.com");
    }
    

    这将为您使用GETPOSTOPTIONS 方法映射的所有请求启用跨源请求。

    【讨论】:

    猜你喜欢
    • 2017-05-25
    • 2020-06-30
    • 2019-12-26
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多