Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

403 Forbidden while doing delete request. Spring boot rest api

So i have backend in java and frontend in Angular. While im sending delete request to my spring boot rest endpoint im getting 403 code. Angular sends first OPTIONS request and it returns this 403 so DELETE request not happens. Additionaly GET and POST works fine.

I have tried disable csrf but it didnt wokred. Also im using it in my browser so i shouldnt disabling this. In soapUI DELETE works fine.

This is my security config class

@Configuration
@EnableWebSecurity
public class AuthConfig extends WebSecurityConfigurerAdapter {

    @Value(value = "${auth0.apiAudience}")
    private String audience;
    @Value(value = "${auth0.issuer}")
    private String issuer;
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JwtWebSecurityConfigurer
                .forRS256(audience, issuer)
                .configure(http)
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,"/public").permitAll()
                .antMatchers(HttpMethod.GET,"/private/**").authenticated()
                .antMatchers(HttpMethod.GET,"/private-scoped").hasAuthority("read:posts");
    }
}

I want to do this delete requests.

@PostMapping("/private/post/{id}/like")
    public void likePostById(@PathVariable Long id){
        postService.likePostById(id);
    }

    @DeleteMapping("/private/post/{id}/like")
    public void unlikePostById(@PathVariable Long id){
        postService.unlikePostById(id);
    }

enter image description here

like image 478
K4mczi Avatar asked May 11 '26 20:05

K4mczi


1 Answers

In case you are on Spring Boot, you can do this, too:

@Bean
public WebMvcConfigurer corsConfigurer()
{
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE", 
            "PATCH", "OPTIONS", "HEAD");
        }
    };
}

You can add your mappings to a particular url as well.

like image 66
Vinay Kumar Avatar answered May 14 '26 11:05

Vinay Kumar