Combined JOSE parsing
To parse arbitrary JOSE objects (plain, signed and encrypted) use the base
JOSEObject
class:
import com.nimbusds.jose.*;
JOSEObject joseObject;
try {
joseObject = JOSEObject.parse(string);
} catch (ParseException e) {
// Invalid JOSE object encoding
}
// Check type of the parsed JOSE object
if (joseObject instanceof PlainObject) {
PlainObject plainObject = (PlainObject)joseObject;
// continue processing of plain object...
} else if (joseObject instanceof JWSObject) {
JWSObject jwsObject = (JWSObject)joseObject;
// continue with signature verification...
} else if (joseObject instanceof JWEObject) {
JWEObject jweObject = (JWEObject)joseObject;
// continue with decryption...
}
Use the JOSEObjectHandler
interface or its JOSEObjectAdapter
to handle
parser output in more elegant and type-safe way, with support for generics:
import com.nimbusds.jose.*;
// Devise a type-self handler for the expected JOSE objects which returns a
// string payload after verification / decryption
class Handler implements JOSEObjectHandler<String> {
@Override
public String onPlainObject(PlainObject plainObject) {
return null; // Plain object payload not recognised
}
@Override
public String onJWSObject(JWSObject jwsObject) {
// Verify signature
boolean success = jwsObject.verify(...);
if (success) {
// Return payload as string
return jwsObject.getPayload().toString();
} else {
return null;
}
}
@Override
public String onJWEObject(JWEObject jweObject) {
// Decrypt
jweObject.decrypt(...);
// Return payload after successful decryption
return jweObject.getPayload().toString();
}
}
// Parse JOSE objects
String content = JOSEObject.parse(string, new Handler(...));