java - 从前端到 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)
我怎样才能获得成功的请求?
解决方案
推荐阅读
- java - openhtmltopdf是否支持外部css
- java - 如何仅绘制传感器的当前数据点?
- c# - 如何在第三个项目中引用和使用 .NET Core 3.0 和 .NET EF 4.7 项目,并使用它们的数据库连接?
- c# - 如何将目标对象围绕 A 轴旋转多少不同的对象围绕 B 轴旋转?
- java - 如何在 Qt 中调用 context.getExternalFilesDir
- java - Appium Send keys() 函数将中文字符作为英文字符串的一部分发送
- java - 发送按钮使应用程序崩溃
- r - Identifying vertex sequences by a criteria
- ruby-on-rails - rails 从参数中选择视图
- apache - 登录 Apache webapp (OpenClinica) 后立即注销