尽管使用CORS,但在使用jHipster oAuth时未经授权的错误

时间:2016-02-23 12:58:34

标签: spring authentication oauth cors jhipster

我正在运行一个带有oAuth身份验证的jHipster实例,并在服务器上启用了CORS。我添加了以下bean:

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.setAllowedMethods(Arrays.asList(new String[]{"GET", "PUT", "POST", "DELETE", "OPTIONS"}));
    source.registerCorsConfiguration("/api/**", config);
    source.registerCorsConfiguration("/v2/api-docs", config);
    source.registerCorsConfiguration("/oauth/**", config);
    return new CorsFilter(source);
}

并添加.antMatchers(HttpMethod.OPTIONS," / oauth / token")。permitAll()到ResourceServerConfiguration配置。

当我尝试从浏览器本地运行的应用程序验证用户(使用服务器上运行的jHipster)时,我得到: 请求方法:选项 - 状态代码:401 Unauthorized

似乎没有正确配置CORS来处理飞行前身份验证POST请求。

我试图在Spring Data Rest and CorsSpring Data Rest and Cors提出一些解决方案无效。

这是否可以在jHipster中完成,以使身份验证能够在浏览器或应用程序中运行(不在jhipster服务器上运行)?

1 个答案:

答案 0 :(得分:4)

我没有注释CORS的行

cors: #By default CORS are not enabled. Uncomment to enable.
    allowed-origins: "*"
    allowed-methods: GET, PUT, POST, DELETE, OPTIONS
    allowed-headers: "*"
    exposed-headers:
    allow-credentials: true
    max-age: 1800

在SecurityConfiguration中添加

            **.antMatchers(HttpMethod.OPTIONS, "/**")**
@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/scripts/**/*.{js,html}")
            .antMatchers("/bower_components/**")
            .antMatchers("/i18n/**")
            .antMatchers("/assets/**")
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/api/register")
            .antMatchers("/api/activate")
            .antMatchers("/api/login/**")
            .antMatchers("/api/account/reset_password/init")
            .antMatchers("/api/account/reset_password/finish")
            .antMatchers("/test/**");
    }

到目前为止它一直在运作。