Enabled CSRF in my Spring MVC application using Spring security 3.2.
My spring-security.xml
<http> <intercept-url pattern="/**/verify" requires-channel="https"/> <intercept-url pattern="/**/login*" requires-channel="http"/> ... ... <csrf /> </http>
Trying to disable CSRF for requests that contain 'verify' in request URL.
MySecurityConfig.java
@Configuration @EnableWebSecurity public class MySecurityConfig extends WebSecurityConfigurerAdapter { private CsrfMatcher csrfRequestMatcher = new CsrfMatcher(); @Override public void configure(HttpSecurity http) throws Exception { http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher); } class CsrfMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { if (request.getRequestURL().indexOf("verify") != -1) return false; else if (request.getRequestURL().indexOf("homePage") != -1) return false; return true; } } }
Csrf filter validates CSRF token that is submitted from 'verify' and Invalid token exception (403) is thrown as I'm submitting request to https from http. How can I disable csrf token authentication in such a scenario ?
Disable using security configuration code The spring boot security application allows to configure the security details in a customized class that extends WebSecurityConfigurerAdapter class. The CSRF feature can be disabled using the code “ http. csrf(). disable ()”.
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.
As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration. If you would like to disable CSRF protection, the corresponding XML configuration can be seen below. CSRF protection is enabled by default with Java Configuration.
What is the real-life reason to disable it? The Spring documentation suggests: Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.
I know this is not a direct answer, but people (as me) usually don't specify spring's version when searching for this kinds of questions. So, since spring security a method exists that lets ignore some routes:
The following will ensure CSRF protection ignores:
http .csrf() .ignoringAntMatchers("/sockjs/**") .and() ...
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