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