首页 > 解决方案 > 从前端到 Java Spring Boot 后端的 CORS 请求出现错误 401

问题描述

我有一个带有React-Native (0.55.1; localhost:8080) 的前端和一个带有 Spring Web Security 的Java 8 Spring Boot (2.0.2; localhost: 8081) 的后端。我想做一个从前端到后端的发布请求以发布一些数据。由于这应该是 CORS 请求,因此我需要配置我的后端以允许处理 CORS 请求。这是我尝试过的(见下文),但如果我向 Spring Boot Server 发布请求,我会不断收到 401(“未经授权”)。这是我的后端配置:

@Configuration
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

    // turn off checking for CSRF tokens
    http.csrf().disable();

    http
            .cors()
            .and()
          .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // **permit OPTIONS call to all**
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated();
            .and()
          .formLogin()
            .loginPage("/api/login")
            .usernameParameter("userName")
            .passwordParameter("password")
            .permitAll()
            .and()
          .logout().logoutUrl("/api/logout");

    http.exceptionHandling().authenticationEntryPoint((req, res, exc) -> res.sendError(HttpServletResponse.SC_UNAUTHORIZED));

    http.formLogin().successHandler((req, res, auth) -> clearAuthenticationAttributes(req));

    http.formLogin().failureHandler((req, res, exc) -> res.sendError(HttpServletResponse.SC_UNAUTHORIZED));

    http.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
    }

@Bean
CorsConfigurationSource corsConfigurationSource() {
   CorsConfiguration configuration = new CorsConfiguration();
   configuration.setAllowedOrigins(Arrays.asList("http://localhost:8081"));
   configuration.setAllowedMethods(Arrays.asList("POST, GET, OPTIONS, DELETE"));
   configuration.setAllowedHeaders(Arrays.asList("*"));
   configuration.setAllowCredentials(true);
   UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
   source.registerCorsConfiguration("/api/**", configuration);
   return source;
  }

我从 localhost:8081 上的 React 客户端使用 Axios(通过 apisauce: https ://github.com/infinitered/apisauce)从前端调用(POST):

import apisauce from 'apisauce'
const create = (baseURL = 'http://localhost:8080/api/') => {
const api = apisauce.create({baseURL,
    headers: {
      'Accept': 'application/json',
      "Content-type": "application/json",
    },
    withCredentials: true,
    dataType: 'json',
    // 10 second timeout...
    timeout: 10000
    })

 // this is the Axios POST request with apisauce 
 api.post('login', data)

我怎样才能获得成功的请求?

标签: javaspringspring-bootreact-nativecors

解决方案


推荐阅读