-1

I have this class to generate a JSON Web token with I got from this post.

I need an id and a expression date to create a token.

Do I have to set up some kind of server to get the id and the expression date?

/**
 * Provides static methods for creating and verifying access tokens and such.
 *
 * @author davidm
 *
 */
public class AuthHelper {

    private static final String AUDIENCE = "NotReallyImportant";

    private static final String ISSUER = "crazyquote";

    private static final String SIGNING_KEY = "LongAndHardToGuessValueWithSpecialCharacters@^($%*$%";

    /**
     * Creates a json web token which is a digitally signed token that contains
     * a payload (e.g. userId to identify the user). The signing key is secret.
     * That ensures that the token is authentic and has not been modified. Using
     * a jwt eliminates the need to store authentication session information in
     * a database.
     *
     * @param userId
     * @param durationDays
     * @return
     */
    public static String createJsonWebToken(String userId, Long durationDays) {
        // Current time and signing algorithm
        Calendar cal = Calendar.getInstance();
        HmacSHA256Signer signer;
        try {
            signer = new HmacSHA256Signer(ISSUER, null, SIGNING_KEY.getBytes());
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        // Configure JSON token
        JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
        token.setAudience(AUDIENCE);
        token.setIssuedAt(new org.joda.time.Instant(cal.getTimeInMillis()));
        token.setExpiration(new org.joda.time.Instant(cal.getTimeInMillis()
                + 1000L * 60L * 60L * 24L * durationDays));

        // Configure request object, which provides information of the item
        JsonObject request = new JsonObject();
        request.addProperty("userId", userId);
        System.out.println("request " + request);
        JsonObject payload = token.getPayloadAsJsonObject();
        payload.add("info", request);

        try {
            return token.serializeAndSign();
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Verifies a json web token's validity and extracts the user id and other
     * information from it.
     *
     * @param token
     * @return
     * @throws SignatureException
     * @throws InvalidKeyException
     */
    public static TokenInfo verifyToken(String token) {
        try {
            final Verifier hmacVerifier = new HmacSHA256Verifier(
                    SIGNING_KEY.getBytes());

            VerifierProvider hmacLocator = new VerifierProvider() {

                @Override
                public List<Verifier> findVerifier(String id, String key) {
                    return Lists.newArrayList(hmacVerifier);
                }
            };
            VerifierProviders locators = new VerifierProviders();
            locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
            net.oauth.jsontoken.Checker checker = new net.oauth.jsontoken.Checker() {

                @Override
                public void check(JsonObject payload) throws SignatureException {
                    // don't throw - allow anything
                }

            };
            // Ignore Audience does not mean that the Signature is ignored
            JsonTokenParser parser = new JsonTokenParser(locators, checker);
            JsonToken jt;
            try {
                jt = parser.verifyAndDeserialize(token);
            } catch (SignatureException e) {
                throw new RuntimeException(e);
            }
            JsonObject payload = jt.getPayloadAsJsonObject();
            TokenInfo t = new TokenInfo();
            String issuer = payload.getAsJsonPrimitive("iss").getAsString();
            String userIdString = payload.getAsJsonObject("info")
                    .getAsJsonPrimitive("userId").getAsString();
            if (issuer.equals(ISSUER) && !StringUtils.isBlank(userIdString)) {
                t.setUserId(new ObjectId(userIdString));
                t.setIssued(new DateTime(payload.getAsJsonPrimitive("iat")
                        .getAsLong()));
                t.setExpires(new DateTime(payload.getAsJsonPrimitive("exp")
                        .getAsLong()));
                return t;
            } else {
                return null;
            }
        } catch (InvalidKeyException e1) {
            throw new RuntimeException(e1);
        }
    }

} 
Community
  • 1
  • 1
user3476614
  • 537
  • 2
  • 8
  • 26

1 Answers1

0

I would expect the user's ID in this context is either the username sent to the application by the user themselves, or some other kind of ID that you can look up based on the principal the user sent. The expiration date you simply choose. How long do you want the token to be valid before the user has to relogin? Now, on the topic of servers, there's nothing in the OAuth2 protocol mandating a server or a web context. What kind of application are you building?

kaqqao
  • 12,984
  • 10
  • 64
  • 118
  • it is a program where the user is authenticated can add different quotes. This is where we write code that is as safe as possible a course from school. And I have tried to implement Token Based Authentication but it has not gone so well so far – user3476614 May 09 '15 at 22:24