001 package com.nimbusds.jwt; 002 003 004 import java.text.ParseException; 005 006 import net.minidev.json.JSONObject; 007 008 import com.nimbusds.jose.Algorithm; 009 import com.nimbusds.jose.Header; 010 import com.nimbusds.jose.JWEAlgorithm; 011 import com.nimbusds.jose.JWSAlgorithm; 012 import com.nimbusds.jose.util.Base64URL; 013 import com.nimbusds.jose.util.JSONObjectUtils; 014 015 016 /** 017 * Parser for plain, signed and encrypted JSON Web Tokens (JWTs). 018 * 019 * @author Vladimir Dzhuvinov 020 * @version $version$ (2013-06-11) 021 */ 022 public final class JWTParser { 023 024 025 /** 026 * Parses a plain, signed or encrypted JSON Web Token (JWT) from the 027 * specified string in compact format. 028 * 029 * @param s The string to parse. Must not be {@code null}. 030 * 031 * @return The corresponding {@link PlainJWT}, {@link SignedJWT} or 032 * {@link EncryptedJWT} instance. 033 * 034 * @throws ParseException If the string couldn't be parsed to a valid 035 * plain, signed or encrypted JWT. 036 */ 037 public static JWT parse(final String s) 038 throws ParseException { 039 040 final int firstDotPos = s.indexOf("."); 041 042 if (firstDotPos == -1) 043 throw new ParseException("Invalid JWT serialization: Missing dot delimiter(s)", 0); 044 045 Base64URL header = new Base64URL(s.substring(firstDotPos)); 046 047 JSONObject jsonObject = null; 048 049 try { 050 jsonObject = JSONObjectUtils.parseJSONObject(header.decodeToString()); 051 052 } catch (ParseException e) { 053 054 throw new ParseException("Invalid plain/JWS/JWE header: " + e.getMessage(), 0); 055 } 056 057 Algorithm alg = Header.parseAlgorithm(jsonObject); 058 059 if (alg.equals(Algorithm.NONE)) { 060 return PlainJWT.parse(s); 061 } else if (alg instanceof JWSAlgorithm) { 062 return SignedJWT.parse(s); 063 } else if (alg instanceof JWEAlgorithm) { 064 return EncryptedJWT.parse(s); 065 } else { 066 throw new AssertionError("Unexpected algorithm type: " + alg); 067 } 068 } 069 070 071 /** 072 * Prevents instantiation. 073 */ 074 private JWTParser() { 075 076 // Nothing to do 077 } 078 }