Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring an AccessDeniedHandler in order to process an invalid csrf token

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

?

like image 409
balteo Avatar asked Mar 18 '15 13:03

balteo


People also ask

How do I pass CSRF token in REST API?

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.

What does CSRF () Disable () do?

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.


1 Answers

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

like image 51
Manu Zi Avatar answered Sep 22 '22 12:09

Manu Zi