I am dealing with a complex manual security configuration (Spring 3.4, Spring Security 3.2). The filter chains have been configured manually with httpSessionContextIntegrationFilter
and other beans configured by us.
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant" request-matcher="ant">
<security:filter-chain pattern="/**" filters="httpSessionContextIntegrationFilter, ... beans ...,filterInvocationInterceptor"/>
</security:filter-chain-map>
</bean>
Now, I need to add CSRF protection. I cannot add http and csrf tags, as http is duplicating the manual config. Instead, I tried to configure this in Java, but the Java config does not add CSRF filter.
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
}
I declared the bean <bean class="package.WebSecurityConfig"/>
in application context, yet WebSecurityConfigurerAdapter.configure method is never called on app context creation.
How can I add CSRF protection here? Do I need to insert CSRFFilter manually as well?
Extract from this link if its answers your question.
import my.filter.CsrfTokenGeneratorFilter;
import org.springframework.security.web.csrf.CsrfFilter;
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new CsrfTokenGeneratorFilter(), CsrfFilter.class);
}
}
/**
* Filter which adds CSRF information as response headers.
*
* @author Patrick Grimard
* @since 12/31/2013 4:48 PM
*/
public final class CsrfTokenGeneratorFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
// Spring Security will allow the Token to be included in this header name
response.setHeader("X-CSRF-HEADER", token.getHeaderName());
// Spring Security will allow the token to be included in this parameter name
response.setHeader("X-CSRF-PARAM", token.getParameterName());
// this is the value of the token to be included as either a header or an HTTP parameter
response.setHeader("X-CSRF-TOKEN", token.getToken());
filterChain.doFilter(request, response);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.