blackdog
blackdog

Reputation: 2107

How to forbid `DELETE` http request in Springboot?

The security department ask us to forbid DELETE and some other http request method if we don't need to use it in our applications. In SpringMVC I can add the security-constraint in web.xml like this:

<security-constraint>  
<display-name>delete-method</display-name>  
<web-resource-collection>  
    <web-resource-name>unsafe-method</web-resource-name>  
    <url-pattern>/*</url-pattern>
    <http-method>DELETE</http-method>
</web-resource-collection>  
<auth-constraint/>  

But I don't know how to add in Springboot. The server is tomcat8.x and run at CentOS.

Upvotes: 2

Views: 398

Answers (1)

htshame
htshame

Reputation: 7330

You can use CORS filter for it. You cas specify allowed HTTP request types there.

Example from the Spring docs:

<mvc:cors>

    <mvc:mapping path="/api/**"
        allowed-origins="http://domain1.com, http://domain2.com"
        allowed-methods="GET, PUT"
        allowed-headers="header1, header2, header3"
        exposed-headers="header1, header2" allow-credentials="false"
        max-age="123" />

    <mvc:mapping path="/resources/**"
        allowed-origins="http://domain1.com" />

</mvc:cors>

OR

You can do it with Java.

Here's the nice implementation

@Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

Upvotes: 1

Related Questions