-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSRF
More file actions
45 lines (38 loc) · 1.64 KB
/
CSRF
File metadata and controls
45 lines (38 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class CSRFProtection {
private static final int TOKEN_LENGTH = 32;
public static String generateToken() {
return SecureRandomUtil.generateToken(TOKEN_LENGTH);
}
public static boolean validateToken(String sessionToken, String requestToken) {
if (sessionToken == null || requestToken == null) {
return false;
}
return MessageDigest.isEqual(
sessionToken.getBytes(),
requestToken.getBytes()
);
}
public static class CSRFFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (isStateChangingMethod(httpRequest.getMethod())) {
String sessionToken = (String) httpRequest.getSession()
.getAttribute("csrf_token");
String requestToken = httpRequest.getHeader("X-CSRF-TOKEN");
if (!validateToken(sessionToken, requestToken)) {
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
"CSRF token validation failed");
return;
}
}
chain.doFilter(request, response);
}
private boolean isStateChangingMethod(String method) {
return "POST".equals(method) || "PUT".equals(method) ||
"DELETE".equals(method) || "PATCH".equals(method);
}
}
}