spring - 如何解决 Spring Boot Post 请求中的 403 错误

标签 spring rest maven spring-boot

我是 Spring Boot Rest 服务的新手。我使用 maven 项目在 spring boot 中开发了一些 rest api。

我已经成功开发了 GetPost 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

请建议我如何解决错误。

enter image description here

最佳答案

你必须禁用 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/

相关文章:

java - Spring MVC Rest App - 加载属性的最佳实践

java - Android 中的 Post 请求 Spring Boot Rest 服务出现 I/O 错误

java - 无法从 Java 中的 CXF REST Web 服务读取或解析纯字符串响应

java - Tomcat 日历 Web 应用程序 mysql : MySQLNonTransientConnectionException:

java - 解决 Tomcat 8.0.15 和 java 8 上的 tomcatproprietaryEvaluate 异常

spring - 400 Hibernate @Valid 错误请求

java - 预期为 : class java. lang.Integer,得到类 org.hibernate.action.internal.DelayedPostInsertIdentifier

spring - Spring @autowired 是否不适用于非单例容器?

java - 用于 Java 的 REST API?

java - 如何将 json 的 Maven 依赖项添加到 >= Java 9 中的模块