Search code examples
spring-bootspring-securitycsrf

SpringSecurity CSRF protection


I have implemented CSRF protection using spring boot & below is how it works:-

  1. 1st time authenticate user using basic auth. and give jsession id and xsrf-token in cookie.
  2. Now this token is available in my cookie. if I try with same session id and token, the api will authenticate me and make post or put requests also.
  3. Now how it is protecting my api from csrf attack.

code -

// implementation of csrf
    CsrfTokenRequestAttributeHandler attributeHandler = new CsrfTokenRequestAttributeHandler();
    attributeHandler.setCsrfRequestAttributeName("_csrf");


.csrf(csrf -> csrf.csrfTokenRequestHandler(attributeHandler)
                    .ignoringRequestMatchers("/contact", "/register")
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
            .addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class)

public class CsrfCookieFilter extends OncePerRequestFilter{

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    
     CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
        if(null != csrfToken.getHeaderName()){
            response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken());
        }
        filterChain.doFilter(request, response);
}

}

Please somebody explain, how do we get protection from csrf?


Solution

  • Assume that your are being target of CSRF attack by EvilCorp, and you are visiting their website. Now in regular scenario you as user do not know what Javascript is being sent by EvilCorp servers to your browser, and your browser would happily execute any (almost) any Javascript code which is sent by EvilCorp when visiting their websites.

    Now if EvilCorp writes some Javascript code which sends requests to your API, then your browser will happily comply, and will include any cookies which are relevant for that origin, thus your browser would include the jsession cookie despite the request being sent from EvilCorp.This means that EvilCorp has managed to make an authenticated request to your API without the user being aware of it. That could be bad!

    In order to prevent the request from succeeding CSRF tokens are used. CSRF tokens are additional cookies, which also need to be included in request headers, in order for request to suceed. For example when you logged in the backend Spring application sent back the XSRF-TOKEN cookie. For any subsequent requests to succeed you will have to include the content of this cookie as HTTP header in your request, otherwise the request will fail.

    Once the request reaches the backend, the backend will check that value of XSRF-TOKEN in cookie is equal to the value in header, and if they match it will execute the request.

    How does this all prevent EvilCorp from sending authenticated requests to your API? Well it turns out that EvilCorp can not read out the XSRF-TOKEN cookie, becuase EvilCorp can only access cookies for its own origin. Because of this EvilCorp can still send out requests to your API, but they will fail and no damage will be done.

    I hope that helps, if more details are needed please leave a comment.