代码之家  ›  专栏  ›  技术社区  ›  Harshal Deshmukh

如何解决春季开机自检请求403错误

  •  11
  • Harshal Deshmukh  · 技术社区  · 7 年前

    我是春季靴托服务的新手。我使用Maven项目在Spring引导中开发了一些RESTAPI。

    我已经成功地发展了 得到 应用程序编程接口。我的 得到 方法在邮递员和移动设备中正常工作。 当我试图从邮递员那里点击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

    2 回复  |  直到 7 年前
        1
  •  31
  •   Ezzat Eissa    7 年前

    您必须禁用CSRF保护,因为它在Spring Security中是默认启用的:在这里您可以看到允许CORS来源的代码。

    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;
        }
    
    }
    
        2
  •  1
  •   desoss    7 年前

    可能的原因:

    1. 来自邮差的请求与来自移动的请求不同(URI、方法、头)
    2. 无效的令牌
    3. CORS(阅读相关内容,谷歌有很多文章)将@crossorigin注释添加到控制器中。
    4. 移动应用程序在执行POST之前正在执行选项请求,您将阻止选项请求。如果来自邮差的选项请求也被阻止,请添加属性 spring.mvc.dispatch options request=真 . 此外,在使用Spring安全性的情况下,还必须显式地允许选项请求。