Reputation: 127
private static final Key secret = MacProvider.generateKey(SignatureAlgorithm.HS256); private static final byte[] secretBytes = secret.getEncoded(); private static final String base64SecretBytes = Base64.getEncoder().encodeToString(secretBytes); private static String generateToken(String subject, String issuer, String audience) { String id = UUID.randomUUID().toString().replace("-", ""); Date now = new Date(); Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds String token = Jwts.builder() .setId(id) .setIssuedAt(now) .setNotBefore(now) .setExpiration(exp) .setSubject(subject) .setIssuer(issuer) .setAudience(audience) .signWith(SignatureAlgorithm.HS256, base64SecretBytes) .compact(); return token; } private static void verifyToken(String token) { Claims claims = Jwts.parser() .setSigningKey(base64SecretBytes) .parseClaimsJws(token).getBody(); System.out.println("----------------------------"); System.out.println("ID: " + claims.getId()); System.out.println("Subject: " + claims.getSubject()); System.out.println("Issuer: " + claims.getIssuer()); System.out.println("Expiration : " + claims.getExpiration()); System.out.println("Not Before : "+claims.getNotBefore()); System.out.println("Audience :: "+claims.getAudience()); }
I have web serves JHipster API and I wrote Java code to connect it and I know the JWT token have three components from JWT web site https://jwt.io/
first Decoded
{ "alg": "HS256", "typ": "JWT" }
secound is PAYLOAD
{ "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
my issue in this part how we know sub,name and iat in JHipster API webserves ?
Upvotes: 1
Views: 1553
Reputation: 293
[UPDATE]
This answer is according to the io.jsonwebtoken:jjwt library
According to the documentation provided on their github page
Jws<Claims> jws;
try {
jws = Jwts.parser() // (1)
.setSigningKey(key) // (2)
.parseClaimsJws(jwsString); // (3)
// we can safely trust the JWT
catch (JwtException ex) { // (4)
// we *cannot* use the JWT as intended by its creator
}
setSigningKey()
is the key you use to protect your JWT. With this key you van verify if your JWT is unchanged and valid.
The parseClaimsJws() is where you set your JWSString as parameter.
After that you should be able to iterate over the claims and read the values
[OLD]
This answer is according to the com.auth0:java-jwt library
In order to get you "claim" you have to decode you JWT. You can do this with the following code:
DecodedJWT decodedJWT = JWT.decode(JWTString);
String sub = decodedJWT.getClaim("sub").asString();
String name = decodedJWT.getClaim("name").asString();
String iat = decodedJWT.getClaim("iat").asInt();
If you also want to verify if the JWT is still valid you can do this by using the JWT verifier:
JWTVerifier verifier = JWT.require("YOUR ALGORITHM").build();
DecodedJWT decodedJWT = verifier.verify(JWTString)
Upvotes: 0