JOSE object / JSON Web Token (JWT) parsing

Parsing JOSE objects or JWTs of a certain expected type (plain, signed or encrypted) is easy. If your application accepts more than one JOSE type see the examples on combined parsing.

JOSE object parsing

To parse plain (unprotected) objects:

import com.nimbusds.jose.*;

PlainObject plainObject;

try {
    plainObject = PlainObject.parse(string);
} catch (java.text.ParseException e) {
    // Invalid plain JOSE object encoding
}

// continue with header and payload extraction...
plainObject.getHeader();
plainObject.getPayload();

To parse HMAC-protected or signed (JWS) objects:

import com.nimbusds.jose.*;

JWSObject jwsObject;

try {
    jwsObject = JWSObject.parse(string);
} catch (java.text.ParseException e) {
    // Invalid JWS object encoding
}

// continue with signature verification...
jwsObject.verify(...);

To parse encrypted (JWE) objects:

import com.nimbusds.jose.*;

JWEObject jweObject;

try {
    jweObject = JWEObject.parse(string);
} catch (java.text.ParseException e) {
    // Invalid JWE object encoding
}

// continue with decryption...
jweObject.decrypt(...);

JWT parsing

To parse plain (unprotected) tokens:

import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;

PlainJWT plainJWT;

try {
    plainJWT = PlainJWT.parse(string);
} catch (java.text.ParseException e) {
    // Invalid plain JWT encoding
}

// continue with header and claims extraction...
plainJWT.getHeader();
plainJWT.getClaimsSet();

To parse HMAC-protected or signed tokens:

import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;

SignedJWT signedJWT;

try {
    signedJWT = SignedJWT.parse(string);
} catch (java.text.ParseException e) {
    // Invalid signed JWT encoding
}

// continue with signature verification...
signedJWT.verify(...);

To parse encrypted (JWE) objects:

import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;

EncryptedJWT encryptedJWT;

try {
    encryptedJWT = EncryptedJWT.parse(string);
} catch (java.text.ParseException e) {
    // Invalid encrypted JWT encoding
}

// continue with decryption...
encryptedJWT.decrypt(...);