How to Validate a JSON Web Token (JWT) in Java

11 Aug 2023 Balmiki Mandal 0 Core Java

Validate JWT Tokens in Java with Examples

JSON Web Tokens (JWT) are commonly used for authentication and authorization between two parties. They are an effective way to secure communications between two parties, and can also be used to store data in a structured format. To ensure the integrity and security of the token, it is important to validate the JWT token before allowing access. Here's how to validate a JWT token in Java.

Step 1: Obtain the JWT Token

Before trying to validate the JWT token, you must first obtain it. Typically, a JWT token is sent over an HTTPS/TLS connection as part of an authentication request. Depending on the authentication process, the JWT token may be sent either as a query string parameter or in the authorization header. Once you have the token, you can proceed to the next step.

Step 2: Decode the Token

In order to validate the token, you'll need to first decode it. This can be done using the JWT Decoder library for Java. The library provides tools for decoding a variety of different tokens, including JWT tokens. The decoded token contains information such as the issuer, audience, expiration date, and the payload.

Step 3: Validate the Token

Now that you have the token decoded, you can validate it. This involves checking the signature, expiration date, and other fields to ensure that the token is valid and trusted. For instance, you can check that the token was issued by a trusted source, that the expiration date has not passed, and that the signature is valid.

Here are the steps to validate a JWT token in Java:

  1. Import the necessary libraries: You will need to import the following libraries:

    • com.nimbusds:nimbus-jose-jwt
    • io.jsonwebtoken:jjwt
  2. Create a JWT parser: You can use the Jwts.parserBuilder() method to create a JWT parser.

  3. Set the signing algorithm and secret key: The signing algorithm and secret key are used to verify the signature of the JWT token. You can get these values from your security team.

  4. Parse the JWT token: You can use the parser.parse() method to parse the JWT token. This will return a JwtClaims object that contains the claims of the JWT token.

  5. Validate the claims: You need to validate the following claims of the JWT token:

    • exp: The expiration time of the token. The token must not have expired.
    • iat: The issue time of the token. The token must not have been issued in the future.
    • iss: The issuer of the token. The issuer must be a trusted issuer.
    • aud: The audience of the token. The token must be intended for the current application.
  6. Verify the signature: You can use the Jwts.parser().verify() method to verify the signature of the JWT token. This method will throw an exception if the signature is invalid.

Here is an example of how to validate a JWT token in Java:

import com.nimbusds.jose.jwt.JwtClaims;
import com.nimbusds.jose.jwt.JwtParser;
import io.jsonwebtoken.Jwts;

public class JwtValidator {

    public static void main(String[] args) {
        // The JWT token
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

        // The signing algorithm and secret key
        String signingAlgorithm = "RS256";
        String secretKey = "my-secret-key";

        // Create a JWT parser
        JwtParser parser = Jwts.parserBuilder().setSigningKey(secretKey).build();

        // Parse the JWT token
        JwtClaims claims = parser.parseClaimsJws(token).getBody();

        // Validate the claims
        long currentTime = System.currentTimeMillis();
        if (claims.getExpirationTime().getTime() < currentTime) {
            throw new RuntimeException("The token has expired");
        }

        if (claims.getIssuedAt().getTime() > currentTime) {
            throw new RuntimeException("The token was issued in the future");
        }

        if (!claims.getIssuer().equals("my-issuer")) {
            throw new RuntimeException("The token was not issued by a trusted issuer");
        }

        if (!claims.getAudience().equals("my-audience")) {
            throw new RuntimeException("The token is not intended for this application");
        }

        // Verify the signature
        parser.verify(token, secretKey);

        System.out.println("The token is valid");
    }
}

Conclusion

Validating a JWT token in Java is a simple process that helps ensure the security and integrity of communications between two parties. By following the steps outlined above, you can quickly validate a JWT token and use it for authentication and authorization.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.