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 private static final long serialVersionUID = 1L; 028 029 030 /** 031 * Creates a new to-be-signed JSON Web Token (JWT) with the specified 032 * header and claims set. The initial state will be 033 * {@link com.nimbusds.jose.JWSObject.State#UNSIGNED unsigned}. 034 * 035 * @param header The JWS header. Must not be {@code null}. 036 * @param claimsSet The JWT claims set. Must not be {@code null}. 037 */ 038 public SignedJWT(final JWSHeader header, final JWTClaimsSet claimsSet) { 039 040 super(header, new Payload(claimsSet.toJSONObject())); 041 } 042 043 044 /** 045 * Creates a new signed JSON Web Token (JWT) with the specified 046 * serialised parts. The state will be 047 * {@link com.nimbusds.jose.JWSObject.State#SIGNED signed}. 048 * 049 * @param firstPart The first part, corresponding to the JWS header. 050 * Must not be {@code null}. 051 * @param secondPart The second part, corresponding to the claims set 052 * (payload). Must not be {@code null}. 053 * @param thirdPart The third part, corresponding to the signature. 054 * Must not be {@code null}. 055 * 056 * @throws ParseException If parsing of the serialised parts failed. 057 */ 058 public SignedJWT(final Base64URL firstPart, final Base64URL secondPart, final Base64URL thirdPart) 059 throws ParseException { 060 061 super(firstPart, secondPart, thirdPart); 062 } 063 064 065 @Override 066 public JWTClaimsSet getJWTClaimsSet() 067 throws ParseException { 068 069 JSONObject json = getPayload().toJSONObject(); 070 071 if (json == null) { 072 throw new ParseException("Payload of JWS object is not a valid JSON object", 0); 073 } 074 075 return JWTClaimsSet.parse(json); 076 } 077 078 079 /** 080 * Parses a signed JSON Web Token (JWT) from the specified string in 081 * compact format. 082 * 083 * @param s The string to parse. Must not be {@code null}. 084 * 085 * @return The signed JWT. 086 * 087 * @throws ParseException If the string couldn't be parsed to a valid 088 * signed JWT. 089 */ 090 public static SignedJWT parse(final String s) 091 throws ParseException { 092 093 Base64URL[] parts = JOSEObject.split(s); 094 095 if (parts.length != 3) { 096 throw new ParseException("Unexpected number of Base64URL parts, must be three", 0); 097 } 098 099 return new SignedJWT(parts[0], parts[1], parts[2]); 100 } 101}