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