403在spring restapi开发期间请求post或put时出错

mtb9vblg  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(298)

我试图在一个应用了spring5+springsecurity5的项目中实现和使用restapi。
在本地运行tomcat后与postman进行测试时 url: http://localhost:8080/api~ 已确认get、post和put等请求正常工作。
我把这个项目上传到https服务器上,在本地 Postman 的服务器上测试api时,
请求(如put和post)中发生403禁止的错误,get请求除外。
当我在google上搜索时,它说springsecurity的csrf问题+cors处理问题。
所以我改变了密码。
Web安全配置

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/").permitAll()                   
                   ~
                   .anyRequest().permitAll()
                .and()
                    .formLogin()
                 ~                  
                .and()
                    .logout()
               ~
                .and()
                    .httpBasic().disable().cors().configurationSource(corsConfigurationSource())
                .and()
                    .sessionManagement()
                    ~
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

WebMVC配置

@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedOrigins("*");
    }

控制器

@CrossOrigin("*")

但是在freflight请求中它通常返回200,但是在这个请求中我仍然得到403。
哪一部分错了?如果您能告诉我,我将不胜感激:)

voj3qocg

voj3qocg1#

在您的配置中,通过httpsecurity builder添加cors过滤器。即

Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
        .........

这将启用由put和post使用的cors飞行前请求。您不需要包括corsconfigurationsource,只要确保您的控制器中也有@crossorigin注解。

相关问题