Anti CSRF Token – JAVA
Using OWASP ESAPI
- Download OWASP ESAPI Library from the ESAPI project page and add it to the library of the project.
- Generate a new CSRF token and add it to user login and store user in HTTP session.
public String resetCSRFToken() { csrfToken = ESAPI.randomizer().getRandomString(8,DefaultEncoder.CHAR_ALPHANUMERICS); return csrfToken; }
3. Add the token as a parameter / hidden field, on any forms or URLs that should be protected.
final static String CSRF_TOKEN_NAME = "cftoken"; public String addCSRFToken(String href) { User user = ESAPI.authenticator().getCurrentUser(); String token = CSRF_TOKEN_NAME + "=" + user.getCSRFToken(); return href.indexOf( '?') != -1 ? href + "&" + token : href + "?" + token; } public String getCSRFToken() { User user = ESAPI.authenticator().getCurrentUser(); if (user == null) return null; return user.getCSRFToken(); }
4. On the server-side, check that the submitted token matches the token from the user object in the session.
public void verifyCSRFToken(HttpServletRequest request) throws IntrusionException { User user = ESAPI.authenticator().getCurrentUser(); if( request.getAttribute(user.getCSRFToken()) != null ) { return; } String token = request.getParameter(CSRF_TOKEN_NAME); if ( !user.getCSRFToken().equals( token ) ) { throw new IntrusionException("Authentication failed", "Possibly forged HTTP request without proper CSRF token detected"); } }
References
https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API
https://www.owasp.org/index.php/Category:OWASP_CSRFGuard_Project
http://code.google.com/p/owasp-esapi-java/downloads/list
Leave a Reply
Want to join the discussion?Feel free to contribute!