java - Spring Security CORS 问题 : "OPTIONS http://localhost:8080/403 ()"

标签 java spring spring-security cors angular-cli

<分区>

我一直在开发一个在我的后端使用 spring + spring security 的项目,最近遇到了一个与 cors 相关的问题:

The first two lines you can see successful api call output, following that chrome attempts to send http request with an options header to my rest service.

前两行您可以看到成功的 api 调用输出,然后是 chrome 尝试向我的 rest 服务发送带有选项 header 的 Http 请求。


我的问题是这个问题的潜在根源是什么?


我在开发中的前端使用角度 CLI 客户端,在我为 spring 安全创建自定义过滤器并添加我的 WebConfigurerAdapter 配置之前,我没有遇到任何 CORS 问题。如果需要,很乐意提供额外的代码。但是我认为这与此无关,因为我删除了过滤器并发生了同样的问题。

在 chrome、firefox 和 ubuntu 浏览器中测试同样的问题。

Angular CLI 成功代理对“/api/[blah]”的调用 Angular CLI is Proxying my rest service

这是我的代理配置,我试过只匹配所有内容,但没有任何区别。

{
"/api/*": {
  "target": "http://localhost:8080",
  "secure": false,
  "logLevel": "debug",
  "changeOrigin": true
}

WebSecurityAdapter 配置

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/index.html",  "/api/registration", "/api/authenticate",
                    "/api/isAuthenticated", "/api/validateCaptcha", "/console", "/api/loginRecaptchaRequired", "/api/login", "/")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .addFilterBefore(
                    authenticationFilter(),
                    UsernamePasswordAuthenticationFilter.class)
            .logout()
            .logoutUrl("/api/logout")
            .and()
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
            .addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class);

}

请求 header : enter image description here

最佳答案

为什么你的代码不工作

您缺少 Access-Control-Allow-Origin header ,因此不允许任何网站向您的网站发出 CORS 请求

修复

您可以:

  • 同源请求
  • 使用 spring security 将 header 添加到响应中
  • 手动添加标题

允许什么来源

header 可以是允许的来源白名单,也可以是 * 以允许任何来源发送请求。

这是否会停止除白名单之外的所有请求

这仅在浏览器中提供保护,恶意软件仍然可以在不遵守 CORS 的情况下向任何端点发出请求。

关于java - Spring Security CORS 问题 : "OPTIONS http://localhost:8080/403 ()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302733/

相关文章:

java - 如何编写接口(interface)自定义保存方法的测试用例

java - 在 Maven 存储库中找不到 SpringSecurityUser 类

java - 将信息传递到构造函数中

java - PHP 和 Java 中类和结构的区别

java - 具有绝对布局的android可回收,具有动态创建的编辑文本,并在新行中自动重复

spring Authentication.setAuthenticated(boolean) java.lang.IllegalArgumentException : Cannot set this token to trusted

java - spring-boot-gradle-plugin 是否随 spring-boot 版本一起移动?

java - 如果用户未登录,则将其重定向到登录页面

java - 登录/使用 Api 与 Spring Security 基本身份验证不起作用

Java:编译错误