尽管有 CORS,但在使用 jHipster oAuth 时出现未经授权的错误
Posted
技术标签:
【中文标题】尽管有 CORS,但在使用 jHipster oAuth 时出现未经授权的错误【英文标题】:Unauthorized Error when using jHipster oAuth despite CORS 【发布时间】:2016-06-05 07:59:40 【问题描述】:我正在运行一个 jHipster 实例,该实例在服务器上启用了 oAuth 身份验证和 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)时,我得到: 请求方法:OPTIONS - 状态码:401 Unauthorized
似乎没有正确配置 CORS 以处理飞行前身份验证 POST 请求。
我尝试实施Spring Data Rest and Cors 和Spring Data Rest and Cors 提出的一些解决方案,但无济于事。
这是否可以在 jHipster 中完成以启用身份验证以从浏览器或应用程序(不在 jhipster 服务器上运行)工作?
【问题讨论】:
您使用的是什么版本的 JHipster?如果是最新版本,您可以通过取消注释 application.yml 中的“cors”部分来启用 CORS。 @MattRaible 嗨,马特,感谢您对此进行调查(顺便说一句,我当然是您的工作和大众汽车的忠实粉丝)。无论如何,我使用的是 jHipster 2.23.0。 CORS 已启用,但如上所述的预检身份验证 POST 存在一些问题。我自己的服务与 CORS 配合得很好。 我也是我的大众汽车的忠实粉丝!我等不及它完成了。 ;) 您是否尝试将这些额外的行添加到 CsrfCookieGeneratorFilter? jhipster.github.io/tips/… @jvence 嗨,这个运气好吗?我遇到了同样的问题.. @i_raqz 抱歉,运气不好。就等jHipster 3.0出来看看是否还存在 【参考方案1】:我取消了 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
在安全配置中添加
**.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/**");
到目前为止它一直在工作。
【讨论】:
以上是关于尽管有 CORS,但在使用 jHipster oAuth 时出现未经授权的错误的主要内容,如果未能解决你的问题,请参考以下文章
JHipster:CORS 在表单登录时失败(实际请求,不是飞行前)
CORS Origin Spring Boot Jhipster - 飞行前失败
使用 JHipster 4 生成的应用程序在 8080 上返回空白页,但在 9000 上没有