【问题标题】:Spring Security CORS issue when passing Authorization header [duplicate]传递授权标头时的Spring Security CORS问题[重复]
【发布时间】:2020-06-02 03:42:56
【问题描述】:

我浪费了很多时间来解决这个问题,但现有的解决方案都不适用于我的情况。 让我解释一下我的服务器设置。 我有 2 个 docker 容器,一个用于 Angular 应用程序(nginx - url - http://localhost:8080)和 Spring Boot 应用程序(tomcat - url - http://localhost:8081)。 此应用正在使用 Oauth2 jdbcToken 身份验证进行 API 请求。

这个应用是一个简单的用户注册应用。

我可以注册一个新用户,因为注册 url 不安全并且没有传递任何授权标头。 但是一旦用户登录 CORS 问题就会出现。下面我列出了错误。

从源“http://localhost:8080”访问“http://localhost:8081/v1/api/group/find/shib”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

让我告诉你我做了什么来解决这个问题。 在 Angular HTTP 请求中,我添加了以下标头。

'Authorization' : 'Bearer '+this.token(),
'Access-Control-Allow-Methods' : '*',
'Access-Control-Allow-Origin' : "*",
'Access-Control-Allow-Headers' : 'Content-Type, Accept, X-Requested-With, remember-me, Authorization',
"Access-Control-Expose-Headers" : "Content-Type, Accept, X-Requested-With, remember-me, Authorization"

在 Spring Boot 中,我在带有 CORSFilter 的 Rest 控制器上添加了 @CrossOrigin / @CrossOrigin("http:localhost:8080")

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {


    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, Authorization");
    chain.doFilter(req, res);
}

经过所有的试验和错误,我仍然得到同样的错误

【问题讨论】:

标签: angularjs spring-boot docker spring-security cors


【解决方案1】:

我阅读并了解了更多关于预检请求及其工作方式的内容。 我的一个快速想法是让 OPTIONS 请求通过,所以我将以下代码添加到我的 WebSecurityConfigurerAdapter。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.OPTIONS,"*").permitAll()//allow CORS option calls
    .antMatchers("/oauth/token").permitAll()
    .anyRequest().authenticated()
    .and()
    .formLogin()
    .and()
    .httpBasic();
}

除了授权之外,Angular ui 没有额外的标头。

我希望这对每个人都有效。我现在知道 OPTIONS 很容易受到攻击,但这只是一个快速的解决方法。 如果您有更好、更安全的解决方案,请建议我。

【讨论】:

  • 当一个AUTHORIZATION头被添加到一个请求中时,浏览器会自动做一个pre-flight OPTIONS请求。服务器必须使用正确的 CORS 标头进行响应。否则浏览器将阻止访问响应。来自 OPTIONS 请求的 OK 状态响应是强制性的。
猜你喜欢
  • 2016-06-25
  • 1970-01-01
  • 2016-10-30
  • 2013-03-06
  • 2017-06-21
  • 2018-12-31
  • 2016-07-01
  • 2019-05-30
相关资源
最近更新 更多