我是 Spring Boot Rest 服务的新手。我使用 maven 项目在 spring boot 中开发了一些 rest api。
我已经成功开发了 Get 和 Post Api。我的 GET 方法在 postman 和移动设备中正常工作。 当我尝试从 postman 发送 post 方法时,它可以正常工作,但从移动端发送 403 禁止错误。
这是我的配置:
spring.datasource.url = jdbc:mysql://localhost/sampledb?useSSL=false
spring.datasource.username = te
spring.datasource.password = test
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
请建议我如何解决错误。
最佳答案
你必须禁用 csrf 保护,因为它在 spring security 中默认启用:在这里你可以看到允许 cors origin 的代码。
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception{
http.cors().and().csrf().disable();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("*"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
关于spring - 如何解决 Spring Boot Post 请求中的 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50486314/