Disclaimer: My question is somewhat similar to this question and this question, but I have tried all the answers suggested in those threads and already spent few days struggling with the problem.
I am introducing Spring Security 3.2.6 in my existing application (JSP, Servlet only) and I am using Java configuration. My application will be used both by browsers and non-browser clients. I want all the browser requests to URLs (i.e. /webpages/webVersion/
and /webpages/webVersion2/
) to be CSRF enabled and all the other requests to be CSRF disabled. Non-browser clients never access above two URLs, whereas the browser application may also access CSRF disabled URLs.
I have tried a variety of options:
Enable Spring Security only on the aformentioned URLs:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/","/resources/****").permitAll() .antMatchers("/webpages/webVersion/****", "/webpages/webVersion2/****").authenticated() .antMatchers("/webpages/****").permitAll() .anyRequest().anonymous() .and() .formLogin().loginPage("/webpages/webVersion/login/newLogin.jsp").failureUrl("/webpages/webVersion/login/newLogin.jsp?error=true").loginProcessingUrl("/j_spring_security_check") .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/webpages/webVersion/login/loginSuccess.jsp", true).permitAll() .and() .logout().logoutUrl("/webpages/webVersion/logout.jsp").permitAll() .and().exceptionHandling().accessDeniedPage("/webpages/webVersion/404-error-page.jsp") .and() .csrf(); }
This didn't work as I observe that CSRF is enabled for all of the URLs.
Tried using
CSRFProtectionMatcher
:.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher);
CSRF is enabled for intended URLs only, but even
/resources/**
and/webpages/**
URLs need to be checked inside matches function. Seems to be a bit much considering it will be for all requests.Tried using another version of the
configure
method:@Override public void configure(WebSecurity web) throws Exception { web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?"); }
I am not sure whether I did it correctly but this didn't produce the results I wanted.
Which of the above approach is the correct (Spring Security) way of doing what I want? How can I achieve the desired behavior from my Spring Security configuration?