I have implemented CSRF protection using spring boot & below is how it works:-
- 1st time authenticate user using basic auth. and give jsession id and xsrf-token in cookie.
- 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.
- 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?