I have a simple rest API which works with database. It worked properly until I added the security part. Now it gives HTTP 405 Not Allowed on the POST and DELETE requests. I have
You forget the csrf
-Token.
It's recommended that you add the csrf-Token in the meta-tag. You can read it in the Spring Security Documentation
With this you can do the following:
$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
I wanted to leave an additional solution, because although Manu Zi's answer is a correct one, it wasn't immediately clear to me why the first time I came across this issue and found this answer.
The underlying issue was obscured by the immediate problem of the 405 Method Not Allowed.
In my case, there were two factors at play. Firstly, there was no POST method for my AccessDenied controller, which resulted in a 405 when a POST method was denied and redirected to the AccessDenied controller. This was only evident after turning up debug logging on org.springframework.web
.
Once that was clear, it was a matter of figuring out why I was getting access denied. All the permissions and roles were correct, but having upgraded from Spring 3 to 4, I found that CSRF protection was enabled by default. It either needs to be disabled, or you have to use Manu Zi's solution.
To disable it, see: spring security 4 csrf disable via xml