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.JWEAlgorithm;
011import com.nimbusds.jose.JWSAlgorithm;
012import com.nimbusds.jose.util.Base64URL;
013import com.nimbusds.jose.util.JSONObjectUtils;
014
015
016/**
017 * Parser for unsecured (plain), signed and encrypted JSON Web Tokens (JWTs).
018 *
019 * @author Vladimir Dzhuvinov
020 * @author Junya Hayashi
021 * @version 2015-06-14
022 */
023public final class JWTParser {
024
025
026        /**
027         * Parses an unsecured (plain), signed or encrypted JSON Web Token
028         * (JWT) from the 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         *                        unsecured, signed or encrypted JWT.
037         */
038        public static JWT parse(final String s)
039                throws ParseException {
040
041                final int firstDotPos = s.indexOf(".");
042                
043                if (firstDotPos == -1)
044                        throw new ParseException("Invalid JWT serialization: Missing dot delimiter(s)", 0);
045                        
046                Base64URL header = new Base64URL(s.substring(0, firstDotPos));
047                
048                JSONObject jsonObject;
049
050                try {
051                        jsonObject = JSONObjectUtils.parse(header.decodeToString());
052
053                } catch (ParseException e) {
054
055                        throw new ParseException("Invalid unsecured/JWS/JWE header: " + e.getMessage(), 0);
056                }
057
058                Algorithm alg = Header.parseAlgorithm(jsonObject);
059
060                if (alg.equals(Algorithm.NONE)) {
061                        return PlainJWT.parse(s);
062                } else if (alg instanceof JWSAlgorithm) {
063                        return SignedJWT.parse(s);
064                } else if (alg instanceof JWEAlgorithm) {
065                        return EncryptedJWT.parse(s);
066                } else {
067                        throw new AssertionError("Unexpected algorithm type: " + alg);
068                }
069        }
070
071
072        /**
073         * Prevents instantiation.
074         */
075        private JWTParser() {
076
077        }
078}