У меня есть интерфейс с React-Native (0.55.1; localhost: 8080) и серверная часть с Java 8 Spring Boot (2.0.2; localhost: 8081) сSpring Web Security.Я хочу сделать пост-запрос от внешнего интерфейса к внутреннему интерфейсу, чтобы отправить некоторые данные.Поскольку это должен быть запрос CORS, мне нужно настроить свой бэкэнд, чтобы разрешить обработку запросов CORS.Это то, что я пытался (см. Ниже), но я продолжаю получать 401 («Несанкционированный»), если я отправляю запрос на Spring Boot Server.Это мой Конфиг для бэкэнда:
@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;
}
Я делаю вызов (POST) из внешнего интерфейса с помощью Axios (через apisauce: https://github.com/infinitered/apisauce) из клиента React на локальном хосте: 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)
Как мне выполнить успешный запрос?