Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Disable CSRF for specific URLs SPA Spring Gateway WebFlux

I have next CSRF code in WebFilterChain:

            .csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse())
            .requireCsrfProtectionMatcher(getURLsForDisabledCSRF())

I would like to turn off the CSRF check on POST methods for several URLs. I have found NegatedServerWebExchangeMatcher, which allows doing next:

        return new NegatedServerWebExchangeMatcher(ServerWebExchangeMatchers.pathMatchers(
HttpMethod.POST, "/services/service1/api/some-post-endpoint1", 
"/services/service1/api/some-post-endpoint2");

So overall this code works, but when I’m trying to GET request login page or domain page, I will get ‘Invalid CSRF’ or ‘Expected CSRF cannot be found’. Also after Spa tries to redirect me to index.html there will be 403 on this GET redirect the request, which says: Invalid CSRF or no CSRF presented.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When setting the requireCsrfProtectionMatcher you override the default configuration which allows GET requests.

If you want to use both, you can return an AndServerWebExchangeMatcher from getURLsForDisabledCSRF that combines the default CSRF matcher and you custom matcher.

new AndServerWebExchangeMatcher(
    CsrfWebFilter.DEFAULT_CSRF_MATCHER,
    new NegatedServerWebExchangeMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST,
        "/services/service1/api/some-post-endpoint1",
        "/services/service1/api/some-post-endpoint2"))
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading