- java
- Spring
- security
- framework specific
- web
- Spring Security
- OWASP Top 10
Secure coding practices prescribe to send CSRF tokens as a request parameter and compare them with a session-stored token.
It is recommended to use a secure random token (e.g., CSRF token) for any state changing operation. There are several ways to safely include CSRF Tokens using Java Spring depending on your context.
Form SubmissionsEnsure that you include the CSRF token in all PATCH, POST, PUT, and DELETE methods. One way to approach this is to use the _csrf request attribute to obtain the current CsrfToken.
Correct code example<c:url var="logoutUrl" value="/logout"/> <form action="${logoutUrl}" method="post"> <input type="submit" value="Log out" /> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> </form>
An easier approach is to use the csrfInput tag from the Spring Security JSP tag library.
If you are using Spring MVC <form:form>
tag or Thymeleaf 2.1+ and are using @EnableWebSecurity
, the CsrfToken is automatically included for you (using the CsrfRequestDataValueProcessor
).
If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead, you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags.
Correct code example:<html> <head> <meta name="_csrf" content="${_csrf.token}"/> <!-- default header name is X-CSRF-TOKEN --> <meta name="_csrf_header" content="${_csrf.headerName}"/> </head>
Instead of manually creating the meta tags, you can use the simpler csrfMetaTags tag from the Spring Security JSP tag library. You can then include the token within all your Ajax requests.
No cookiesUsing a cookie does not work. All cookies, even the secret ones, will be submitted with every request. All authentication tokes will be submitted regardless of whether the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.
id: scw:spring:websecurity-debug-enabled version: 10 metadata: name: 'Security Misconfiguration: EnableWebSecurity with Debug enabled' shortDescription: The debug parameter on EnableWebSecurity should not be hardcoded to true level: warning language: java scwCategory: misconfig:debug enabled: true comment: "" descriptionFile: descriptions/Security_Misconfiguration__EnableWebSecurity_with_Debug_enabled.html tags: Spring;security;framework specific;web;Spring Security;OWASP Top 10 search: annotationParameter: name: debug value: value: stringified: "true" availableFixes: - name: Fix the code by setting debug to false actions: - rewrite: to: debug = false