Search code examples
javaspringspring-securitycsrf

spring security get csrf token in java area


When using spring security, we can use CSRF token. We may use in spring security xml, and in jsp

> (<sec:csrfInput /> or <input type=”hidden”
> name=”${_csrf.parameterName}” value=”${_csrf.token}”/>).

But how do I get the csrf token name and value in Java area?

I have to send a mail to users from service layer in my web app. And csrf token must exist inside of mail contents.

String html = new String( "<div style='width:600px; height:300px; margin:0 auto;'>" +
                "<h2 style='color:#FFBB00;'>lock release system</h2>" + 
                "<p style='color:#2F9D27'>your account has been locked. If you want to release the lock, you should click 'release user lock' button below." +
                "</p>" +
                "<hr>" +
                "<form action='http://122.40.73.117:9000/whiteboard/user/release-lock-user' method='post' target='_blank'>" +
                    "<input type='hidden' name='email' value='" + email + "' />" + 
                    "<input type='hidden' name='csrf' value='" + csrf + "' />" + 
                    "<button type='submit' style='font-weight:bold;'>release user lock</button>" + 
                "</form>" +     
            "</div>");

The code above uses CSRF variable, but that is just a dummy variable. How do I set CSRF ?


Solution

  • org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository handles the csrf tokens. It defines a method org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository#loadToken

    which basically does

    CsrfToken token
    =session.getAttribute("HttpSessionCsrfTokenRepository.CSRF_TOKEN");
    

    You can try the same in your code, but need access to the HttpRequest or HttpSession, which should not be a problem.

    One csrf token belongs always to one session. So your code in the mail will only work, if the user is connected via the mail browser to exactly the same session he used, when the csrf token was generated. This may be a problem if he opens the mail on another device, or after the session timed out.

    A Csrf token is meant to be a secret between client and server to improve security. Sending a csrf token via an insecure channel like mail does eliminate that security gain.