Search code examples
javaspringspring-mvcspring-securitycsrf

Get _csrf in spring controller


How can I get _csrf object (?!) in spring controller? I've configured Spring Security and can get ${_csrf} request attribute in jsp files. I've tried:

CsrfToken _csrf = (CsrfToken) session.getAttribute("CsrfToken");
CsrfToken _csrf = (CsrfToken) session.getAttribute("_csrf");

the result is null;

Thanks in advance!


Solution

  • In debug I saw a session attribute with a key "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN". I viewed the HttpSessionCsrfTokenRepository class. It has a method for loading token from incoming HttpServletRequest object.

    Finally this worked for me:

    CsrfToken token = new HttpSessionCsrfTokenRepository().loadToken(request);
    

    I will be grateful if someone explains me how this works.