【问题标题】:Spring boot security post request not working with corsSpring Boot 安全发布请求不适用于 cors
【发布时间】:2022-01-01 16:56:22
【问题描述】:

我正在使用 spring boot 框架,我已经实现了两个 rest 端点类型 get 和 type post 请求。 如果我们从同一来源访问这些端,则获取和发布请求工作正常。 当我尝试从反应应用程序访问这些端点时,Get 请求工作正常,但是当我点击第二个端点(发布请求)时,状态码为 401。我在浏览器控制台中找不到任何 cors 错误
前端代码。

const _HEADERS = {
    'Content-Type': 'application/json',
    'x-xsrf-token': getCSRFToken(),
    'Authorization': 'Basic ' + btoa("admin" + ":" + "admin")
}

let fetchData = async  (resource:string, method:string, postData:Object, mode:string = _SAME_ORGIN, formData:any = null, headers:any = _HEADERS ) => {
    let initObj = {};
    if( method === "GET" ) {
        initObj = {
            method: method,
            mode: mode,
            cache: 'no-cache',
            headers: headers
          };
    } else {
        initObj = {
            method: method,
            mode: mode,
            cache: 'no-cache',
            headers: headers,
            body: formData === null? JSON.stringify(postData): formData
        };
    }
    
    return await fetch( new Request(resource, initObj) );
}

后端代码

Global cors
@Bean
    public WebMvcConfigurer configure() {
        return new WebMvcConfigurer() {
            @Override
            public void  addCorsMappings(CorsRegistry registry) {
                Boolean corsEnabled = Boolean.parseBoolean( environment.getProperty("application.cors.enabled"));
                if( corsEnabled != null && corsEnabled == true ) {
                    registry.addMapping("/**").allowedOrigins("http://localhost:8000");
                }
            }
        };
    }

Security
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 
        .and().authorizeRequests((requests) -> requests.anyRequest().authenticated());
        http.formLogin();
        http.httpBasic();
        if (corsEnabled != null && corsEnabled == true) {
            http.cors();
        }

【问题讨论】:

  • Access-Control-Allow-*response 标头,而不是 request 标头。花时间阅读和理解developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  • 另外,“发布请求不起作用”是什么意思。提供更多细节。您是否在浏览器的“控制台”选项卡中观察到 CORS 错误?如果是这样,错误消息说明了什么?
  • 休息端点,方法类型 POST。获取状态码 401。我找不到任何 cors 错误。
  • CORS 必须在 Spring Security 之前处理,因为飞行前请求不会包含任何 cookie。见docs.spring.io/spring-security/site/docs/4.2.x/reference/html/…
  • 需要更多的安全配置细节。 401 表示未经授权的错误。所以它与您的基本身份验证或您配置端点安全配置的方式有关。

标签: javascript reactjs spring-boot cors


【解决方案1】:

更新安全性。

http.csrf().disable().authorizeRequests((requests) -> requests.anyRequest().authenticated());
        http.formLogin();
        http.httpBasic();
        if (corsEnabled != null && corsEnabled == true) {
            http.cors();
        }

【讨论】:

    猜你喜欢
    • 2018-11-07
    • 2016-01-15
    • 2019-05-25
    • 2017-03-10
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    相关资源
    最近更新 更多