001package com.nimbusds.jwt; 002 003 004import java.text.ParseException; 005 006import net.jcip.annotations.ThreadSafe; 007 008import net.minidev.json.JSONObject; 009 010import com.nimbusds.jose.JOSEObject; 011import com.nimbusds.jose.JWSHeader; 012import com.nimbusds.jose.JWSObject; 013import com.nimbusds.jose.Payload; 014import com.nimbusds.jose.util.Base64URL; 015 016 017/** 018 * Signed JSON Web Token (JWT). 019 * 020 * @author Vladimir Dzhuvinov 021 * @version 2015-08-19 022 */ 023@ThreadSafe 024public class SignedJWT extends JWSObject implements JWT { 025 026 027 /** 028 * Creates a new to-be-signed JSON Web Token (JWT) with the specified 029 * header and claims set. The initial state will be 030 * {@link com.nimbusds.jose.JWSObject.State#UNSIGNED unsigned}. 031 * 032 * @param header The JWS header. Must not be {@code null}. 033 * @param claimsSet The JWT claims set. Must not be {@code null}. 034 */ 035 public SignedJWT(final JWSHeader header, final JWTClaimsSet claimsSet) { 036 037 super(header, new Payload(claimsSet.toJSONObject())); 038 } 039 040 041 /** 042 * Creates a new signed JSON Web Token (JWT) with the specified 043 * serialised parts. The state will be 044 * {@link com.nimbusds.jose.JWSObject.State#SIGNED signed}. 045 * 046 * @param firstPart The first part, corresponding to the JWS header. 047 * Must not be {@code null}. 048 * @param secondPart The second part, corresponding to the claims set 049 * (payload). Must not be {@code null}. 050 * @param thirdPart The third part, corresponding to the signature. 051 * Must not be {@code null}. 052 * 053 * @throws ParseException If parsing of the serialised parts failed. 054 */ 055 public SignedJWT(final Base64URL firstPart, final Base64URL secondPart, final Base64URL thirdPart) 056 throws ParseException { 057 058 super(firstPart, secondPart, thirdPart); 059 } 060 061 062 @Override 063 public JWTClaimsSet getJWTClaimsSet() 064 throws ParseException { 065 066 JSONObject json = getPayload().toJSONObject(); 067 068 if (json == null) { 069 throw new ParseException("Payload of JWS object is not a valid JSON object", 0); 070 } 071 072 return JWTClaimsSet.parse(json); 073 } 074 075 076 /** 077 * Parses a signed JSON Web Token (JWT) from the specified string in 078 * compact format. 079 * 080 * @param s The string to parse. Must not be {@code null}. 081 * 082 * @return The signed JWT. 083 * 084 * @throws ParseException If the string couldn't be parsed to a valid 085 * signed JWT. 086 */ 087 public static SignedJWT parse(final String s) 088 throws ParseException { 089 090 Base64URL[] parts = JOSEObject.split(s); 091 092 if (parts.length != 3) { 093 throw new ParseException("Unexpected number of Base64URL parts, must be three", 0); 094 } 095 096 return new SignedJWT(parts[0], parts[1], parts[2]); 097 } 098}