Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2014
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.47 KB | None | 0 0
  1. <dependency>
  2. <groupId>com.google.guava</groupId>
  3. <artifactId>guava</artifactId>
  4. <version>18.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.googlecode.jsontoken</groupId>
  8. <artifactId>jsontoken</artifactId>
  9. <version>1.0</version>
  10. </dependency>
  11.  
  12. import java.security.InvalidKeyException;
  13. import java.security.SignatureException;
  14. import java.util.Calendar;
  15. import java.util.List;
  16.  
  17. import net.oauth.jsontoken.JsonToken;
  18. import net.oauth.jsontoken.JsonTokenParser;
  19. import net.oauth.jsontoken.crypto.HmacSHA256Signer;
  20. import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
  21. import net.oauth.jsontoken.crypto.SignatureAlgorithm;
  22. import net.oauth.jsontoken.crypto.Verifier;
  23. import net.oauth.jsontoken.discovery.VerifierProvider;
  24. import net.oauth.jsontoken.discovery.VerifierProviders;
  25.  
  26. import org.apache.commons.lang3.StringUtils;
  27. import org.bson.types.ObjectId;
  28. import org.joda.time.DateTime;
  29.  
  30. import com.google.common.collect.Lists;
  31. import com.google.gson.JsonObject;
  32. import com.google.wallet.online.jwt.util.IgnoreAudience;
  33.  
  34. /**
  35. * Provides static methods for creating and verifying access tokens and such.
  36. * @author davidm
  37. *
  38. */
  39. public class AuthHelper {
  40.  
  41. private static final String AUDIENCE = "NotReallyImportant";
  42.  
  43. private static final String ISSUER = "YourCompanyOrAppNameHere";
  44.  
  45. private static final String SIGNING_KEY = "PutAPrettyLongAndHardToGuessValueHereShouldIncludeSpecialCharacters";
  46.  
  47. /**
  48. * Creates a json web token which is a digitally signed token that contains a payload (e.g. userId to identify
  49. * the user). The signing key is secret. That ensures that the token is authentic and has not been modified.
  50. * Using a jwt eliminates the need to store authentication session information in a database.
  51. * @param userId
  52. * @param durationDays
  53. * @return
  54. */
  55. public static String createJsonWebToken(String userId, Long durationDays) {
  56. //Current time and signing algorithm
  57. Calendar cal = Calendar.getInstance();
  58. HmacSHA256Signer signer;
  59. try {
  60. signer = new HmacSHA256Signer(ISSUER, null, SIGNING_KEY.getBytes());
  61. } catch (InvalidKeyException e) {
  62. throw new RuntimeException(e);
  63. }
  64.  
  65. //Configure JSON token
  66. JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
  67. token.setAudience(AUDIENCE);
  68. token.setIssuedAt(new org.joda.time.Instant(cal.getTimeInMillis()));
  69. token.setExpiration(new org.joda.time.Instant(cal.getTimeInMillis() + 1000L * 60L * 60L * 24L * durationDays));
  70.  
  71. //Configure request object, which provides information of the item
  72. JsonObject request = new JsonObject();
  73. request.addProperty("userId", userId);
  74.  
  75. JsonObject payload = token.getPayloadAsJsonObject();
  76. payload.add("info", request);
  77.  
  78. try {
  79. return token.serializeAndSign();
  80. } catch (SignatureException e) {
  81. throw new RuntimeException(e);
  82. }
  83. }
  84.  
  85. /**
  86. * Verifies a json web token's validity and extracts the user id and other information from it.
  87. * @param token
  88. * @return
  89. * @throws SignatureException
  90. * @throws InvalidKeyException
  91. */
  92. public static TokenInfo verifyToken(String token)
  93. {
  94. try {
  95. final Verifier hmacVerifier = new HmacSHA256Verifier(SIGNING_KEY.getBytes());
  96.  
  97. VerifierProvider hmacLocator = new VerifierProvider() {
  98.  
  99. @Override
  100. public List<Verifier> findVerifier(String id, String key){
  101. return Lists.newArrayList(hmacVerifier);
  102. }
  103. };
  104. VerifierProviders locators = new VerifierProviders();
  105. locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
  106.  
  107. //Ignore Audience does not mean that the Signature is ignored
  108. JsonTokenParser parser = new JsonTokenParser(locators,
  109. new IgnoreAudience());
  110. JsonToken jt;
  111. try {
  112. jt = parser.verifyAndDeserialize(token);
  113. } catch (SignatureException e) {
  114. throw new RuntimeException(e);
  115. }
  116. JsonObject payload = jt.getPayloadAsJsonObject();
  117. TokenInfo t = new TokenInfo();
  118. String issuer = payload.getAsJsonPrimitive("iss").getAsString();
  119. String userIdString = payload.getAsJsonObject("info").getAsJsonPrimitive("userId").getAsString();
  120. if (issuer.equals(ISSUER) && !StringUtils.isBlank(userIdString))
  121. {
  122. t.setUserId(new ObjectId(userIdString));
  123. t.setIssued(new DateTime(payload.getAsJsonPrimitive("iat").getAsLong()));
  124. t.setExpires(new DateTime(payload.getAsJsonPrimitive("exp").getAsLong()));
  125. return t;
  126. }
  127. else
  128. {
  129. return null;
  130. }
  131. } catch (InvalidKeyException e1) {
  132. throw new RuntimeException(e1);
  133. }
  134. }
  135.  
  136.  
  137. }
  138.  
  139. public class TokenInfo {
  140. private ObjectId userId;
  141. private DateTime issued;
  142. private DateTime expires;
  143. public ObjectId getUserId() {
  144. return userId;
  145. }
  146. public void setUserId(ObjectId userId) {
  147. this.userId = userId;
  148. }
  149. public DateTime getIssued() {
  150. return issued;
  151. }
  152. public void setIssued(DateTime issued) {
  153. this.issued = issued;
  154. }
  155. public DateTime getExpires() {
  156. return expires;
  157. }
  158. public void setExpires(DateTime expires) {
  159. this.expires = expires;
  160. }
  161. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement