Haifeng Zhang
Haifeng Zhang

Reputation: 31905

PUT/DELETE got 403 Error but GET/POST works

There's a Spring Boot application running on the back-end. I have implemented a couple of GET/POST/PUT/DELETE APIs.

The front-end(AngularJS) can do GET and POST, but it would get 403 ERROR when request PUT and DELETE. I have added the allowed origins(POST wouldn't work without it) to solve CORS issue.

CORS Settings:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("https://xxx1.com", "https://xxx2.com");
        }
    };
}

CSRF Settings:

  http.csrf().disable();

It is disabled for now

Below is my implementation of DELETE:

   @DeleteMapping("/listings/{id}")
    public ResponseEntity<Void> deleteListings(@PathVariable Long id) {
        log.debug("REST request to delete listings : {}", id);
        this.listingsService.delete(id);
        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

Can anyone help? Really appreciated!

Upvotes: 3

Views: 9754

Answers (2)

hrdkisback
hrdkisback

Reputation: 908

Create CORSFilter.java file in your spring-boot project.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    /**
     * CORS filter for http-request and response
     */
    public CORSFilter() {
    }

    /**
     * Do Filter on every http-request.
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    /**
     * Destroy method
     */
    @Override
    public void destroy() {
    }

    /**
     * Initialize CORS filter 
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}

You can refer this post Angular 2 Spring Boot Login CORS Problems

Upvotes: 2

Adam Jenkins
Adam Jenkins

Reputation: 55782

Looks like you can chain on an allowedMethods("GET","POST","PUT","DELETE") according to the docs.

Does that helps?

Upvotes: 3

Related Questions