I am in reference to Spring Security documentation about configuring CSRF protection:
Instead by default Spring Security’s CSRF protection will produce an HTTP 403 access denied. This can be customized by configuring the AccessDeniedHandler to process InvalidCsrfTokenException differently.
see here: http://docs.spring.io/spring-security/site/docs/3.2.6.RELEASE/reference/htmlsingle/#csrf-configure
I am unsure how to configure my handler in order to deal with the invalid CSRF token.
private AccessDeniedHandler accessDeniedHandler() {
return new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
// TODO: deal with InvalidCsrfTokenException
response.setStatus(HttpStatus.FORBIDDEN.value());
}
};
}
I use angular on the client side to communicate with my Spring app in REST.
What is the best way to deal with stale/invalid CSRF tokens?
Should I use the the AccessDeniedHandler
in order to add a custom http response header indicating that the CSRF token is invalid and process that on the client side? But how can I request a fresh CSRF token from JS?
Is there another and better way to proceed and how can I
process the InvalidCsrfTokenException differently
?
The CSRF token is stored in the client. The CSRF token is required for any later REST API calls. The client must send a valid token with every API request. The token is sent in a custom request HTTP header.
But till now in all our examples we had disabled CSRF. CSRF stands for Cross-Site Request Forgery. It is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.
If you provide a detailed error message then use the AccessDeniedHandler
. The handler manage the InvalidCsrfTokenException
and MissingCsrfTokenException
And why do you want to generate the csrf token? Everytime you request a site spring will generate it for you. But if you really want to implement an own csrf strategie take a look at the CsrfAuthenticationStrategy
Spring call this class everytime in the SessionManagementFilter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With