Skip to content

Instantly share code, notes, and snippets.

@richardgill
Last active July 7, 2017 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save richardgill/6ac1d45cc3ad3ae06b16952facf15951 to your computer and use it in GitHub Desktop.
Save richardgill/6ac1d45cc3ad3ae06b16952facf15951 to your computer and use it in GitHub Desktop.
JWT Example (Java)

#Login via HTTP JSON api to get JWT token

##Client does login request

POST https://myapplication.com/login, body: {username: 'richardgill', password: 'password'}

Server receives request. Takes credentials and checks they are correct.

Server uses secret key: "secretkey123!" to generate a jwt token. (Using jwt library)

//See method at bottom
signJwtToken("secretkey123!", username)

returns {token: "jwtjwtjwt.tokentokentoken.hereherehere"}

Client saves the jwt token somewhere in the browser (e.g. local storage).

##Subsequent authenticated requests

All subsequent authenticated requests always pass the jwt token somewhere (http header is quite regular).

GET /accounts with header: "jwtjwtjwt.tokentokentoken.hereherehere"

Server receives request with header.

//Can throw
Map<String,Object> claims = verifyJwtToken(secret, jwtToken);
String username = claims.get("username");

//You now know they are definitely that username
//Go get customers if that username is allowed to.

##Helper functions (pseudo java based on jwt library)

//throws an exception if jwttoken not valid.
static public Map<String,Object> verifyJwtToken(secret, jwtToken) {
  final JWTVerifier verifier = new JWTVerifier(secret);
  return jwtVerifier.verify(jwtToken);
}

public static signJwtToken(secretKey, username) {
  final String issuer = "https://mydomain.com/";

  final long iat = System.currentTimeMillis() / 1000l; // issued at claim 
  final long exp = iat + 60L; // expires claim. In this case the token expires in 60 seconds
  
  final JWTSigner signer = new JWTSigner(secretKey);
  final HashMap<String, Object> claims = new HashMap<String, Object>();
  claims.put("iss", issuer);
  claims.put("exp", exp);
  claims.put("iat", iat);
  
  claims.put("username", username);
  
  return signer.sign(claims);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment