Chir
Chir

Reputation: 691

Spring security for CSRF

I am building an application where authentication is done by external system. For CSRF handling, I would like to use Spring Security's CSRF suport (http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html)

I tried various options but could not use Spring Security's CSRF support without authentication.

Is it possible to use only CSRF support from Spring Security? (I do not want to use authentication/authorization)

Upvotes: 0

Views: 1228

Answers (1)

Bala
Bala

Reputation: 19

I also had the same requirement as you , and I was able to achieve it by minimal configurations in spring-security.xml

<authentication-manager />
<http create-session="never" use-expressions="true">
    <csrf />
    <http-basic />
</http>

Here the < authentication-manager /> declares that the spring security doesn't expect an authentication/authorization mechanism, and assumes that all URLs inside the application are already authenticated.

After this add the Spring Security Filter on your web.xml file. This ensures that all requests first pass through spring security mechanism before being handled by the application controller.

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Then in your JSPs (preferably the Header JSP), include the Spring Security's Taglib to access and store the CSRF tokens in the meta tag.

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>

<sec:csrfMetaTags />

<script type="text/javascript">
    var csrfHeader = $("meta[name='_csrf_header']").attr("content");
    var csrfToken = $("meta[name='_csrf']").attr("content");
</script>

After this include the CSRF Tokens in all your Ajax calls. If not included, you will get the 403 - Access Denied Error.

For Example, if you are using jQuery for doing ajax calls, then you can configure it globally to include the CSRF tokens in the Request Header.

$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(csrfHeader, csrfToken);
});

JAR files required for this to work are:

    spring-security-acl-5.0.7.RELEASE.jar
    spring-security-config-5.0.7.RELEASE.jar
    spring-security-core-5.0.7.RELEASE.jar
    spring-security-taglibs-5.0.7.RELEASE.jar
    spring-security-web-5.0.7.RELEASE.jar

Upvotes: 0

Related Questions