-
Notifications
You must be signed in to change notification settings - Fork 3
/
CSRFTokenManager.java
54 lines (46 loc) · 1.49 KB
/
CSRFTokenManager.java
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
46
47
48
49
50
51
52
53
54
package com.javan.security;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* A manager for the CSRF token for a given session. The {@link #getTokenForSession(HttpSession)} should used to obtain
* the token value for the current session (and this should be the only way to obtain the token value).
*/
public final class CSRFTokenManager {
/**
* The token parameter name
*/
static final String CSRF_PARAM_NAME = "xToken";
/**
* The location on the session which stores the token
*/
public final static String CSRF_TOKEN_FOR_SESSION_ATTR_NAME = CSRFTokenManager.class.getName() + ".tokenval";
public static String getTokenForSession(HttpSession session) {
String token = null;
// cannot allow more than one token on a session - in the case of two requests trying to
// init the token concurrently
synchronized (session) {
token = (String) session.getAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME);
if (null == token) {
token = UUID.randomUUID().toString();
session.setAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME, token);
}
}
return token;
}
/**
* Extracts the token value from the session
*
* @param request
* @return
*/
public static String getTokenFromRequest(HttpServletRequest request) {
String token = request.getParameter(CSRF_PARAM_NAME);
if (token == null || "".equals(token)) {
token = request.getHeader(CSRF_PARAM_NAME);
}
return token;
}
private CSRFTokenManager() {
};
}