Roberto Sánchez
2013-12-26 6d04b0ae0f4eeb9f0963b1595d0f2e7469fa5f3f
securis/src/main/java/net/curisit/securis/utils/TokenHelper.java
....@@ -22,6 +22,9 @@
2222
2323 private static final Logger log = LoggerFactory.getLogger(TokenHelper.class);
2424
25
+ /**
26
+ * Period before token expires, set in hours.
27
+ */
2528 private static int VALID_TOKEN_PERIOD = 24;
2629
2730 @Inject
....@@ -30,6 +33,12 @@
3033
3134 private static byte[] seed = "S3Cur15S33dForT0k3nG3n3r@tion".getBytes();
3235
36
+ /**
37
+ * Generate a token encoded in Base64 for user passed as parameter and taking the current moment as token timestamp
38
+ *
39
+ * @param user
40
+ * @return
41
+ */
3342 public String generateToken(String user) {
3443 try {
3544 Date date = new Date();
....@@ -50,7 +59,7 @@
5059
5160 }
5261
53
- public String generateSecret(String user, Date date) throws UnsupportedEncodingException, NoSuchAlgorithmException {
62
+ private String generateSecret(String user, Date date) throws UnsupportedEncodingException, NoSuchAlgorithmException {
5463 MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
5564 mDigest.update(seed, 0, seed.length);
5665 byte[] userbytes = user.getBytes("utf-8");
....@@ -62,6 +71,12 @@
6271 return secret;
6372 }
6473
74
+ /**
75
+ * Check if passed token is still valid, It use to check if token is expired the attribute VALID_TOKEN_PERIOD (in hours)
76
+ *
77
+ * @param token
78
+ * @return
79
+ */
6580 public boolean validateToken(String token) {
6681 try {
6782 String tokenDecoded = new String(Base64.decode(token));
....@@ -69,18 +84,30 @@
6984 String secret = parts[0];
7085 String user = parts[1];
7186 Date date = Utils.toDateFromIso(parts[2]);
72
- if (new Date(new Date().getTime() + 25 * 60 * 60 * 1000).after(new Date(date.getTime() + VALID_TOKEN_PERIOD * 60 * 60 * 1000)))
87
+ if (new Date().after(new Date(date.getTime() + VALID_TOKEN_PERIOD * 60 * 60 * 1000)))
7388 return false;
7489 String newSecret = generateSecret(user, date);
7590 return newSecret.equals(secret);
7691 } catch (IOException e) {
77
- log.error("Error decoding Bse64 token", e);
92
+ log.error("Error decoding Base64 token", e);
7893 } catch (NoSuchAlgorithmException e) {
7994 log.error("Error generation secret to compare with", e);
8095 }
8196 return false;
8297 }
8398
99
+ public String extractUserFromToken(String token) {
100
+ try {
101
+ String tokenDecoded = new String(Base64.decode(token));
102
+ String[] parts = StringUtils.split(tokenDecoded, ' ');
103
+ String user = parts[1];
104
+ return user;
105
+ } catch (IOException e) {
106
+ log.error("Error decoding Base64 token", e);
107
+ }
108
+ return null;
109
+ }
110
+
84111 public static void main(String[] args) throws IOException {
85112 TokenHelper th = new TokenHelper();
86113 String token = th.generateToken("pepe");