Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auth0 JWT with Java

Tags:

java

jwt

auth0

I implemented JSON Web Tokens using this library Aut0 Java JWT for my REST API which uses the Spring Framework.

Here is the code

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;

public class JWTutils {
    private final static String secret = "fj32Jfv02Mq33g0f8ioDkw";

    public static String createToken(String email)
    {
        try {
            return JWT.create()
                    .withIssuer("auth0")
                    .withClaim("email", email)
                    .sign(Algorithm.HMAC256(secret));
        } catch (JWTCreationException exception){
            throw new RuntimeException("You need to enable Algorithm.HMAC256");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static String getEmailInToken(String token)
    {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
                    .withIssuer("auth0")
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("email").asString();
        } catch (JWTDecodeException exception){
            return null;
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
}

Is my JWT secure as long as I use HTTPS? Should I use expiration dates?

like image 449
Elbbard Avatar asked Sep 15 '26 22:09

Elbbard


1 Answers

Yes & No!, your code seems to be OK!

JWT is to put something encrypted in client's computer(like cookies) and then it is the ticket for your api.(We usually use jwt in OAuth )

You can make sure that your data in client's computer has not been modified. Then it is excellent option for small distributed session management.

Should I use expiration dates?

Yes especially for session management.You don't want a user to be logined forever and maybe another user be able to steal his session.This token is now his username & password. Be careful about this!

Is it secure?!

Security has constraints and one important one is time.Every password is breakable but in its time.You'd better change your secret once in a while.

Though Your code seems to be secure but there are many other circumstances that hacker can break into your system and get your secret. You should be aware about them too.All parts of your code including your system must have acceptable security level. Remember:

A chain is only as strong as its weakest link

like image 153
Behdad Avatar answered Sep 17 '26 12:09

Behdad