In this post under JJWT I will show with example how to check whether a JWT is signed or unsigned.
JwtParser class has a “isSigned” method which will figure out whether the JWT is signed or not. All we need is to pass the test JWT string as an argument to this method.
This method returns true or false, true means JWT is signed or else false.
Below is the complete code
Main Class
1 package defaultPackage;
2 import io.jsonwebtoken.JwtParser;
3 import io.jsonwebtoken.JwtParserBuilder;
4 import io.jsonwebtoken.Jwts;
5
6 public class Example3 {
7 public static void main(String[] args) {
8 JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder();
9 JwtParser jwtParser = jwtParserBuilder.build();
10 boolean result = jwtParser.isSigned("eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNjYxMDczNDU5LCJuYWVtIjoiU3VtYW50aCJ9.");
11 System.out.println(result);
12
13 result = jwtParser.isSigned("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
14 System.out.println(result);
15 }
16 }
In the above code, first we create an instance of JwtParser class. Refer to line 8 to 9.
At line 10, we call “isSigned” method and pass the JWT token as an argument.
At line 11, we print the result.
Similar to line 10, at line 13, we call “isSigned” method and pass the JWT token as an argument. This time we are passing a signed JWT.
At line 14, we print the result.
Below is the output
Output
false
true