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