我的前端是 React-Native (0.55.1; localhost:8080),后端是 Java 8 Spring Boot (2.0.2; localhost:8081使用Spring Web Security。我想从前端到后端做一个post请求POST一些数据。由于这应该是一个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;
}
我从React客户端使用Axios(通过apisauce:https://github.com/infinitered/apisauce)从前端进行调用(POST) 在localhost:8081:
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)
如何获得成功请求?