Search code examples
javaspringpostspring-securityhttp-status-code-405

POST request gets 405 response instead of being handled by access-denied-handler


This happens in a Spring MVC application where Spring Security is also used. I have configured request with mapping "/user/save" so that only admins have access to it:

<intercept-url pattern="/user/save/**" access="hasAnyAuthority('ROLE_ADMIN')"/>
<intercept-url pattern="/user/**" access="hasAnyAuthority('ROLE_ADMIN','ROLE_OPERATOR'"/>

Unauthorized requests are handled by

<access-denied-handler error-page="/denied"/>

When I make /user/save request having only ROLE_OPERATOR I get the following warning:

WARN http-nio-8080-exec-20 servlet.PageNotFound:208 - Request method 'POST' not supported

and /denied doesn't get hit. Why?

Answers to similar problems propose configuring csrf for POST queries, but POST queries work for ROLE_ADMIN so that shouldn't be the problem here.

I tried specifying method types in security configuration like this:

<intercept-url pattern="/user/save/**" access="hasAnyAuthority('ROLE_ADMIN')" method="GET"/>
<intercept-url pattern="/user/save/**" access="hasAnyAuthority('ROLE_ADMIN')" method="POST"/>

but it didn't help.

Access denied handler works correctly in other cases, gets hit when requests are made with insufficient privileges, so that shouldn't be a part of the problem either.

What could cause this behavior?


Solution

  • In my case the problem was in the controller method for /denied request. It had a GET version, but not a POST version. Adding a POST version like this:

    @RequestMapping(value = "/denied", method = RequestMethod.POST)
    public @ResponseBody Response userAccessDeniedForPost() {
        ...
    }
    

    solved the problem.