我在使用axios发送HTTP POST请求时遇到问题。每次我得到错误代码403.在客户端我有以下代码:
axios.post(this.props.hostPath+'/api/post',
{
crossdomain: true,
headers: {
'Authorization': this.props.token,
'Access-Control-Request-Method': 'POST'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
在服务器端,在Spring Boot中,我有:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login", "/register").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.GET, "/v2/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedOrigins("http://localhost:8000")
.allowedMethods("PUT", "DELETE", "POST", "GET", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization");
}
};
}
}`
当我在'/ api / post'端点上禁用安全性时,一切正常。提前感谢您的帮助。