TokenMngUtil.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82 |
package framework.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
public class TokenMngUtil {
private static final String TOKEN_KEY = "TOKEN_KEY";
private static final Logger logger = Logger.getLogger(TokenMngUtil.class.getName());
/**
* 로직처리를 위해 세션과 request에 Token 생성
*
* @param request
*/
public static void saveToken(ModelAndView mv, HttpServletRequest request) {
HttpSession session = request.getSession(true);
long systemTime = System.currentTimeMillis();
byte[] time = new Long(systemTime).toString().getBytes();
byte[] id = session.getId().getBytes();
try {
MessageDigest SHA = MessageDigest.getInstance("SHA-256");
SHA.update(id);
SHA.update(time);
String token = Base64.encodeBase64(SHA.digest()).toString();
request.setAttribute(TOKEN_KEY, token);
session.setAttribute(TOKEN_KEY, token);
mv.addObject(TOKEN_KEY, token);
logger.error("#########################################################################");
logger.error("# Generate Token Key Value = " + token + " #");
logger.error("#########################################################################");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 로직처리 이후 중복방지를 위해 세션의 Token 초기화
*
* @param request
*/
public static void resetToken(HttpServletRequest request) {
HttpSession session = request.getSession(true);
try {
session.removeAttribute(TOKEN_KEY);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 세션과 request의 Token이 동일한지 비교
*
* @param request
* @return
*/
public static boolean isTokenValid(HttpServletRequest request) {
HttpSession session = request.getSession(true);
String requestToken = request.getParameter(TOKEN_KEY);
String sessionToken = (String) session.getAttribute(TOKEN_KEY);
if (requestToken == null || sessionToken == null) {
return false;
} else {
return requestToken.equals(sessionToken);
}
}
}
|
TOKEN_KEY generate
1
2 |
/* 중복방지 Token 생성 */
TokenMngUtil.saveToken(mv, req); |
TOKEN_KEY check & session value delete
1
2
3
4
5
6
7 |
if(!TokenMngUtil.isTokenValid(req)){
log.error("잘못된 접근입니다. 중복방지 Token error");
ifsr.addString("resultCode", "Token_error");
return ifsr;
}
/*중복방지 Token 초기화*/
TokenMngUtil.resetToken(req); |
TOKEN_KEY parameter setting
1
2 |
<input type="hidden" name="TOKEN_KEY" id="TOKEN_KEY" value="${TOKEN_KEY}" />
<%-- 중복방지 token parameter --%> |
'programming > java' 카테고리의 다른 글
SAX split the data element problem (0) | 2014.07.18 |
---|---|
Javadoc Tutorial (0) | 2013.05.16 |
refactoring (0) | 2013.01.09 |