Java decode jwt token

JSON Web Token in Java using Auth0 Java JWT Library

In this Java tutorial, we learn how to work with JSON Web Token (JWT) in Java application using the Auth0’s Java JWT library.

How to add Java JWT Library to your Java project

To use the Java JWT library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'com.auth0:java-jwt:3.14.0'

To use the Java JWT library in the Maven build project, add the following dependency into the pom.xml file.

To have more information about the Java JWT library you can visit the library home page at github.com/auth0/java-jwt

How to generate a new JSON web token

In the following example, we generate a new JSON web token with 2 claim values username and role.

import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; public class GenerateJWTExample  public static void main(String. args)  String secret = "123@abc"; Algorithm algorithm = Algorithm.HMAC512(secret); String generatedToken = JWT.create() .withIssuer("Simple Solution") .withClaim("username", "TestUser") .withClaim("role", "User") .sign(algorithm); System.out.println(generatedToken); > >
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsInVzZXJuYW1lIjoiVGVzdFVzZXIifQ.jQUKIOxN0KGbIGJx8SU3WfSVPNASOnRtt3DcoMVBeThcWGzEBAnwlHHYRvbzuas-sOeWSvOwrnsvpQ5tywAfWA

In the following Java program, we learn to generate a JWT token that will expire in 1 minute.

import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import java.util.Date; public class GenerateJWTWithExpireExample  public static void main(String. args)  String secret = "123@abc"; Algorithm algorithm = Algorithm.HMAC512(secret); long expireTime = (new Date().getTime()) + 60000; // 60000 milliseconds = 60 seconds = 1 minute Date expireDate = new Date(expireTime); String generatedToken = JWT.create() .withIssuer("Simple Solution") .withClaim("username", "TestUser") .withClaim("role", "User") .withExpiresAt(expireDate) .sign(algorithm); System.out.println(generatedToken); > >
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsImV4cCI6MTYxNjA4MDAzOCwidXNlcm5hbWUiOiJUZXN0VXNlciJ9.S96EHjYKfWfB4TEXqUBfIJVOEBkOWD9wd37OhIJ4TcxTND9Igni0pHiMB-i3efxSaiiQEGvi-pMrwGKISue1MA

How to verify the a JSON web token

Verify the token without expiration date time.

import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; public class VerifyJWTExample  public static void main(String. args)  String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsInVzZXJuYW1lIjoiVGVzdFVzZXIifQ.jQUKIOxN0KGbIGJx8SU3WfSVPNASOnRtt3DcoMVBeThcWGzEBAnwlHHYRvbzuas-sOeWSvOwrnsvpQ5tywAfWA"; String secret = "123@abc"; Algorithm algorithm = Algorithm.HMAC512(secret); try  JWTVerifier verifier = JWT.require(algorithm) .withIssuer("Simple Solution") .build(); DecodedJWT decodedJWT = verifier.verify(token); System.out.println("Verify JWT token success."); System.out.println("Claims: " + decodedJWT.getClaims()); > catch (JWTVerificationException ex)  System.out.println("Verify JWT token fail: " + ex.getMessage()); > > >
Verify JWT token success. Claims:

Verify the token with expiration date time.

import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; public class VerifyJWTWithExpireExample  public static void main(String. args)  String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsImV4cCI6MTYxNjA4MDEyMCwidXNlcm5hbWUiOiJUZXN0VXNlciJ9.bw87xWcl23Nefzeilnww84kUxvz3Yal90Va6DQogsRhVWvZe_TvmzFkib4ecIKbScMCQnR4a-w3JfaKBw7btNw"; String secret = "123@abc"; Algorithm algorithm = Algorithm.HMAC512(secret); try  JWTVerifier verifier = JWT.require(algorithm) .withIssuer("Simple Solution") .acceptExpiresAt(60) // 60 seconds = 1 minute .build(); DecodedJWT decodedJWT = verifier.verify(token); System.out.println("Verify JWT token success."); System.out.println(decodedJWT.getClaims()); > catch (JWTVerificationException ex)  System.out.println("Verify JWT token fail: " + ex.getMessage()); > > >

How to decode a given JSON web token

In the following Java program, we learn how to decode a given JSON web token and show its issuer and claims data.

import com.auth0.jwt.JWT; import com.auth0.jwt.interfaces.DecodedJWT; public class DecodeJWTExample  public static void main(String. args)  String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsInVzZXJuYW1lIjoiVGVzdFVzZXIifQ.jQUKIOxN0KGbIGJx8SU3WfSVPNASOnRtt3DcoMVBeThcWGzEBAnwlHHYRvbzuas-sOeWSvOwrnsvpQ5tywAfWA"; DecodedJWT decodedJWT = JWT.decode(token); System.out.println("Issuer: " + decodedJWT.getIssuer()); System.out.println("Claims: " + decodedJWT.getClaims()); > >
Issuer: Simple Solution Claims:

Implement a reusable JWTService class

At this step, we learn how to implement a reusable class to generate, verify and decode JSON web tokens that can reuse for your Java project.

import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.Date; public class JWTService  private long DEFAULT_EXPIRE_IN_SECONDS = 60; private String secret = "123@abc"; private Algorithm algorithm = Algorithm.HMAC256(secret); public String generateJWTToken(String username, String role)  long now = new Date().getTime(); long expireTime = now + (DEFAULT_EXPIRE_IN_SECONDS * 1000); Date expireDate = new Date(expireTime); String jwtToken = JWT.create() .withIssuer("Simple Solution") .withClaim("username", username) .withClaim("role", role) .withExpiresAt(expireDate) .sign(algorithm); return jwtToken; > public boolean verifyJWTToken(String token)  try  JWTVerifier verifier = JWT.require(algorithm) .withIssuer("Simple Solution") .acceptExpiresAt(DEFAULT_EXPIRE_IN_SECONDS) .build(); verifier.verify(token); return true; > catch (JWTVerificationException ex)  return false; > > public String getClaimFromToken(String token, String claimKey)  DecodedJWT decodedJWT = JWT.decode(token); return decodedJWT.getClaims().get(claimKey).toString(); > >

Example program how to use JWTService class.

public class JWTExamples  public static void main(String[] args)  JWTService jwtService = new JWTService(); String token = jwtService.generateJWTToken("TestUser", "User"); boolean result = jwtService.verifyJWTToken(token); System.out.println("Generated Token: " + token); System.out.println("Verify Result: " + result); System.out.println("Token Claim, username: " + jwtService.getClaimFromToken(token, "username")); System.out.println("Token Claim, role: " + jwtService.getClaimFromToken(token, "role")); > >
Generated Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiVXNlciIsImlzcyI6IlNpbXBsZSBTb2x1dGlvbiIsImV4cCI6MTYxNjA4MDM0MywidXNlcm5hbWUiOiJUZXN0VXNlciJ9.4NLv-75XG-uyz-3YjnuRau7aKOOUagJ9szdWDR-OR7k Verify Result: true Token Claim, username: "TestUser" Token Claim, role: "User"

Conclusion

In this Java JSON web token tutorial, we have learned how to use the Java JWT library to generate a new token, verify and decode a given token. We also implement a reusable Java class to reuse for different Java projects.

Источник

How to decode JWT token in Java

Decode JWT token in Java

knopka

JWT tokens are used very often for authentication purposes. Let’s try to decode information encoded in JWT tokens.

Let’s asume we’ve got a JWT authentication token from some authentication service. It might look like

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4g RG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Structure of JWT authentication token

There is the information encoded in the JWT token.

You can use the online service jwt.io to decode the JWT token and get the content of the token. In the “PAYLOAD: DATA” section you’ll see.

 "sub": "1234567890", "name": "John Doe", "admin": true >

Decode JWT token in Java.

Our goal is to get that information programmatically — decode a JWT token in Java code.

Here we use Base64 decoding to decode a JWT token.

String[] pieces = encodedToken.split("\\."); String b64payload = pieces[1]; String jsonString = new String(Base64.decodeBase64(b64payload), "UTF-8");

jsonString variable contains the JSON string we’re looking for. So now we know the structure of the JWT authentication token. Knowing that we can create the class DecodedToken . We encapsulate the JWT decoding functionality in the DecodedToken class

import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.codec.binary.Base64; import java.io.UnsupportedEncodingException; public class DecodedToken  public String sub; public String name; public Boolean admin; public static DecodedToken getDecoded(String encodedToken) throws UnsupportedEncodingException  String[] pieces = encodedToken.split("\\."); String b64payload = pieces[1]; String jsonString = new String(Base64.decodeBase64(b64payload), "UTF-8"); return new Gson().fromJson(jsonString, DecodedToken.class); > public String toString()  Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(this); > >

Decode JWT token. Usage example in Java

DecodedToken token = DecodedToken.getDecoded(stringToken);

Now you can access any field of the JWT token

if (token.admin)  System.out.println("Welcome sir " + token.name); > else  System.out.println("Get out. "); >

You may also find these posts interesting:

Источник

Читайте также:  Сколько учить javascript чтобы устроиться
Оцените статью