Combined JWT parsing
To parse tokens with any protection (plain, signed and encrypted) use the
JWTParser
class:
import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;
JWT jwt;
try {
jwt = JWTParser.parse(string);
} catch (ParseException e) {
// Invalid JWT encoding
}
// Check the JWT type
if (jwt instanceof PlainJWT) {
PlainJWT plainObject = (PlainJWT)jwt;
// continue processing of plain JWT...
} else if (jwt instanceof SignedJWT) {
SignedJWT jwsObject = (SignedJWT)jwt;
// continue with signature verification...
} else if (jwt instanceof EncryptedJWT) {
EncryptedJWT jweObject = (EncryptedJWT)jwt;
// continue with decryption...
}
Use the JWTHandler
interface or its JWTAdapter
to handle parser output in
more elegant and type-safe way, with support for generics:
import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;
// Devise a type-self handler for the expected JWTs which returns the claims
// set after verification / decryption
class Handler implements JWTHandler<ReadOnlyJWTClaimsSet> {
@Override
public ReadOnlyJWTClaimsSet onPlainJWT(PlainJWT plainJWT) {
return null; // Plain object claims not accepted
}
@Override
public ReadOnlyJWTClaimsSet onSignedJWT(SignedJWT signedJWT) {
// Verify signature
boolean success = signedJWT.verify(...);
if (success) {
// Return claims
return signedJWT.getClaimsSet();
} else {
return null;
}
}
@Override
public ReadOnlyJWTClaimsSet onEncryptedJWT(EncryptedJWT encryptedJWT) {
// Decrypt
encryptedJWT.decrypt(...);
// Return claims after successful decryption
return encryptedJWT.getClaimsSet();
}
}
// Parse JWTs
ReadOnlyClaimsSet claims = JWTParser.parse(string, new Handler(...));