要解决Axios身份验证请求无法发送头信息给Spring Boot的问题,可以尝试以下解决方法:
withCredentials为true,以便将身份验证头信息发送给Spring Boot。axios.get('http://example.com/api', {
withCredentials: true
});
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("*")
.allowedHeaders("Authorization", "Content-Type")
.allowCredentials(true);
}
};
}
}
上述代码中,通过allowedHeaders方法允许包含Authorization头信息的请求,并通过allowCredentials方法允许跨域请求发送身份验证信息。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
上述代码中,通过.cors()方法启用跨域请求配置,并通过.antMatchers("/**").permitAll()配置允许所有请求跨域访问。
通过上述解决方法,Axios就能够成功发送身份验证头信息给Spring Boot了。