oltu-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From simonetrip...@apache.org
Subject svn commit: r1480619 - in /oltu/trunk/oauth-2.0/jwt: ./ src/main/java/org/apache/oltu/oauth2/jwt/
Date Thu, 09 May 2013 13:16:12 GMT
Author: simonetripodi
Date: Thu May  9 13:16:12 2013
New Revision: 1480619

URL: http://svn.apache.org/r1480619
Log:
OLTU-78 - Implement Plaintext JWT

initial checkin of plaintext JWT support

Added:
    oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java   (with
props)
    oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java   (with
props)
    oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtils.java
      - copied, changed from r1480569, oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtil.java
Removed:
    oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtil.java
Modified:
    oltu/trunk/oauth-2.0/jwt/pom.xml
    oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWT.java

Modified: oltu/trunk/oauth-2.0/jwt/pom.xml
URL: http://svn.apache.org/viewvc/oltu/trunk/oauth-2.0/jwt/pom.xml?rev=1480619&r1=1480618&r2=1480619&view=diff
==============================================================================
--- oltu/trunk/oauth-2.0/jwt/pom.xml (original)
+++ oltu/trunk/oauth-2.0/jwt/pom.xml Thu May  9 13:16:12 2013
@@ -31,6 +31,11 @@
 
   <dependencies>
     <dependency>
+      <groupId>org.codehaus.jettison</groupId>
+      <artifactId>jettison</artifactId>
+    </dependency>
+
+    <dependency>
       <groupId>commons-codec</groupId>
       <artifactId>commons-codec</artifactId>
     </dependency>

Added: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java
URL: http://svn.apache.org/viewvc/oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java?rev=1480619&view=auto
==============================================================================
--- oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java (added)
+++ oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java Thu May
 9 13:16:12 2013
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.oltu.oauth2.jwt;
+
+import static java.lang.String.format;
+
+/**
+ * Represents the Claims Set as defined in the 6.1 section of the JWT specification.
+ *
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-6.1
+ */
+public final class ClaimsSet {
+
+    /**
+     * The {@code iss} JWT Claims Set parameter.
+     */
+    private final String issuer;
+
+    /**
+     * The {@code sub} JWT Claims Set parameter.
+     */
+    private final String subject;
+
+    /**
+     * The {@code aud} JWT Claims Set parameter.
+     */
+    private final String audience;
+
+    /**
+     * The {@code exp} JWT Claims Set parameter.
+     */
+    private final long expirationTime;
+
+    /**
+     * The {@code nbf} JWT Claims Set parameter.
+     */
+    private final String notBefore;
+
+    /**
+     * The {@code iat} JWT Claims Set parameter.
+     */
+    private final long issuedAt;
+
+    /**
+     * The {@code jti} JWT Claims Set parameter.
+     */
+    private final String jwdId;
+
+    /**
+     * The {@code typ} JWT Claims Set parameter.
+     */
+    private final String type;
+
+    ClaimsSet(String issuer,
+              String subject,
+              String audience,
+              long expirationTime,
+              String notBefore,
+              long issuedAt,
+              String jwdId,
+              String type) {
+        this.issuer = issuer;
+        this.subject = subject;
+        this.audience = audience;
+        this.expirationTime = expirationTime;
+        this.notBefore = notBefore;
+        this.issuedAt = issuedAt;
+        this.jwdId = jwdId;
+        this.type = type;
+    }
+
+    /**
+     * Returns the {@code iss} JWT Claims Set parameter.
+     *
+     * @return the {@code iss} JWT Claims Set parameter.
+     */
+    public String getIssuer() {
+        return issuer;
+    }
+
+    /**
+     * Returns the {@code sub} JWT Claims Set parameter.
+     *
+     * @return the {@code sub} JWT Claims Set parameter.
+     */
+    public String getSubject() {
+        return subject;
+    }
+
+    /**
+     * Returns the {@code aud} JWT Claims Set parameter.
+     *
+     * @return the {@code aud} JWT Claims Set parameter.
+     */
+    public String getAudience() {
+        return audience;
+    }
+
+    /**
+     * Returns the {@code exp} JWT Claims Set parameter.
+     *
+     * @return the {@code exp} JWT Claims Set parameter.
+     */
+    public long getExpirationTime() {
+        return expirationTime;
+    }
+
+    /**
+     * Returns the {@code nbf} JWT Claims Set parameter.
+     *
+     * @return the {@code nbf} JWT Claims Set parameter.
+     */
+    public String getNotBefore() {
+        return notBefore;
+    }
+
+    /**
+     * Returns the {@code iat} JWT Claims Set parameter.
+     *
+     * @return the {@code iat} JWT Claims Set parameter.
+     */
+    public long getIssuedAt() {
+        return issuedAt;
+    }
+
+    /**
+     * Returns the {@code jti} JWT Claims Set parameter.
+     *
+     * @return the {@code jti} JWT Claims Set parameter.
+     */
+    public String getJwdId() {
+        return jwdId;
+    }
+
+    /**
+     * Returns the {@code typ} JWT Claims Set parameter.
+     *
+     * @return the {@code typ} JWT Claims Set parameter.
+     */
+    public String getType() {
+        return type;
+    }
+
+    @Override
+    public String toString() {
+        return format("{\"iss\": \"%s\", \"sub\": \"%s\", \"aud\": \"%s\", \"exp\": %s, \"nbf\":
\"%s\", \"iat\": %s, \"jti\": \"%s\" }",
+                      issuer, subject, audience, expirationTime, notBefore, issuedAt, jwdId,
type);
+    }
+
+}

Propchange: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/ClaimsSet.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java
URL: http://svn.apache.org/viewvc/oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java?rev=1480619&view=auto
==============================================================================
--- oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java (added)
+++ oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java Thu May
 9 13:16:12 2013
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.oltu.oauth2.jwt;
+
+import static java.lang.String.format;
+
+/**
+ * Represents the Header as defined in the 6.1 section of the JWT specification.
+ *
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-6.1
+ */
+public final class Header {
+
+    /**
+     * The {@code typ} JWT Header parameter.
+     */
+    private final String type;
+
+    /**
+     * The {@code alg} JWT Header parameter.
+     */
+    private final String algorithm;
+
+    /**
+     * The {@code cty} JWT Header parameter.
+     */
+    private final String contentType;
+
+    Header(String type, String algorithm, String contentType) {
+        this.type = type;
+        this.algorithm = algorithm;
+        this.contentType = contentType;
+    }
+
+    /**
+     * Returns the {@code typ} JWT Header parameter.
+     *
+     * @return the {@code typ} JWT Header parameter.
+     */
+    public String getType() {
+        return type;
+    }
+
+    /**
+     * Returns the {@code alg} JWT Header parameter.
+     *
+     * @return the {@code alg} JWT Header parameter.
+     */
+    public String getAlgorithm() {
+        return algorithm;
+    }
+
+    /**
+     * Returns the {@code cty} JWT Header parameter.
+     *
+     * @return the {@code cty} JWT Header parameter.
+     */
+    public String getContentType() {
+        return contentType;
+    }
+
+    @Override
+    public String toString() {
+        return format("{\"typ\": \"%s\", \"alg\": \"%s\", \"cty\": \"%s\"}", type, algorithm,
contentType);
+    }
+
+}

Propchange: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/Header.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWT.java
URL: http://svn.apache.org/viewvc/oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWT.java?rev=1480619&r1=1480618&r2=1480619&view=diff
==============================================================================
--- oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWT.java (original)
+++ oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWT.java Thu May  9
13:16:12 2013
@@ -16,44 +16,284 @@
  */
 package org.apache.oltu.oauth2.jwt;
 
+import static java.lang.String.format;
+
 /**
  * This class contains constants used in the JWT implementation.
- * 
+ *
  */
 public class JWT {
 
     /**
-     * This inner class contains reserved claims defined in the JWT
-     * specification
+     * The JWT Header as defined in the 6.1 section of the JWT specification.
+     */
+    private final Header header;
+
+    /**
+     * The JWT Claims Set as defined in the 6.1 section of the JWT specification.
+     */
+    private final ClaimsSet claimsSet;
+
+    /**
+     * The JWT Signature.
+     */
+    private final String signature;
+
+    JWT(Header header, ClaimsSet claimsSet, String signature) {
+        this.header = header;
+        this.claimsSet = claimsSet;
+        this.signature = signature;
+    }
+
+    /**
+     * Get the JWT Header as defined in the 6.1 section of the JWT specification.
+     *
+     * @return the JWT Header.
+     * @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-6.1
      */
-    public static final class ReservedClaim {
-        public static final String ISSUER = "iss";
-        public static final String SUBJECT = "sub";
-        public static final String AUDIENCE = "aud";
-        public static final String EXPIRATION_TIME = "exp";
-        public static final String NOT_BEFORE = "nbf";
-        public static final String ISSUED_AT = "iat";
-        public static final String JWT_ID = "jti";
-        public static final String TYPE = "typ";
+    public Header getHeader() {
+        return header;
     }
 
     /**
-     * This inner class contains JWT header parameters
-     * 
+     * Get the JWT Claims Set as defined in the 6.1 section of the JWT specification.
+     *
+     * @return the JWT Claims Set
+     * @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-6.1
      */
-    public static final class HeaderParam {
-        public static final String TYPE = "typ";
-        public static final String ALGORITHM = "alg";
-        public static final String CONTENT_TYPE = "cty";
+    public ClaimsSet getClaimsSet() {
+        return claimsSet;
     }
 
     /**
-     * This inner class contains defined values for JWT header parameters
+     * Get the JWT Signature.
+     *
+     * @return the JWT Signature.
      */
-    public static final class HeaderParamValue {
-        public static final String TYPE_JWT = "JWT";
-        public static final String ALG_HS256 = "HS256";
-        public static final String ALG_NONE = "none";
+    public String getSignature() {
+        return signature;
+    }
+
+    @Override
+    public String toString() {
+        return format("-- JWT --%nHeader: %s%nClaims Set: %s%nSignature: %s%n---------",
header, claimsSet, signature);
+    }
+
+    /**
+     * A simple {@link JWT} builder.
+     */
+    public static final class Builder {
+
+        /**
+         * The {@code typ} JWT Header parameter.
+         */
+        private String headerType;
+
+        /**
+         * The {@code alg} JWT Header parameter.
+         */
+        private String headerAlgorithm;
+
+        /**
+         * The {@code cty} JWT Header parameter.
+         */
+        private String headerContentType;
+
+        /**
+         * The {@code iss} JWT Claims Set parameter.
+         */
+        private String claimsSetIssuer;
+
+        /**
+         * The {@code sub} JWT Claims Set parameter.
+         */
+        private String claimsSetSubject;
+
+        /**
+         * The {@code aud} JWT Claims Set parameter.
+         */
+        private String claimsSetAudience;
+
+        /**
+         * The {@code exp} JWT Claims Set parameter.
+         */
+        private long claimsSetExpirationTime;
+
+        /**
+         * The {@code nbf} JWT Claims Set parameter.
+         */
+        private String claimsSetNotBefore;
+
+        /**
+         * The {@code iat} JWT Claims Set parameter.
+         */
+        private long claimsSetIssuedAt;
+
+        /**
+         * The {@code jti} JWT Claims Set parameter.
+         */
+        private String claimsSetJwdId;
+
+        /**
+         * The {@code typ} JWT Claims Set parameter.
+         */
+        private String claimsSetType;
+
+        /**
+         * The JWT Signature.
+         */
+        private String signature;
+
+        /**
+         * Sets the JWT Header {@code typ}.
+         *
+         * @param headerType the JWT Header {@code typ}.
+         * @return this builder instance.
+         */
+        public Builder setHeaderType(String headerType) {
+            this.headerType = headerType;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Header {@code alg}.
+         *
+         * @param headerAlgorithm the JWT Header {@code alg}.
+         * @return this builder instance.
+         */
+        public Builder setHeaderAlgorithm(String headerAlgorithm) {
+            this.headerAlgorithm = headerAlgorithm;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Header {@code cty}.
+         *
+         * @param headerContentType the JWT Header {@code cty}.
+         * @return this builder instance.
+         */
+        public Builder setHeaderContentType(String headerContentType) {
+            this.headerContentType = headerContentType;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code iss}.
+         *
+         * @param claimsSetIssuer the JWT Claims Set {@code iss}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetIssuer(String claimsSetIssuer) {
+            this.claimsSetIssuer = claimsSetIssuer;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code sub}.
+         *
+         * @param claimsSetSubject the JWT Claims Set {@code sub}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetSubject(String claimsSetSubject) {
+            this.claimsSetSubject = claimsSetSubject;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code aud}.
+         *
+         * @param claimsSetAudience the JWT Claims Set {@code aud}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetAudience(String claimsSetAudience) {
+            this.claimsSetAudience = claimsSetAudience;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code exp}.
+         *
+         * @param claimsSetExpirationTime the JWT Claims Set {@code exp}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetExpirationTime(long claimsSetExpirationTime) {
+            this.claimsSetExpirationTime = claimsSetExpirationTime;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code nbf}.
+         *
+         * @param claimsSetNotBefore the JWT Claims Set {@code nbf}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetNotBefore(String claimsSetNotBefore) {
+            this.claimsSetNotBefore = claimsSetNotBefore;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code issuedAt}.
+         *
+         * @param claimsSetIssuedAt the JWT Claims Set {@code issuedAt}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetIssuedAt(long claimsSetIssuedAt) {
+            this.claimsSetIssuedAt = claimsSetIssuedAt;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code jti}.
+         *
+         * @param claimsSetJwdId the JWT Claims Set {@code jti}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetJwdId(String claimsSetJwdId) {
+            this.claimsSetJwdId = claimsSetJwdId;
+            return this;
+        }
+
+        /**
+         * Sets the JWT Claims Set {@code typ}.
+         *
+         * @param claimsSetType the JWT Claims Set {@code typ}.
+         * @return this builder instance.
+         */
+        public Builder setClaimsSetType(String claimsSetType) {
+            this.claimsSetType = claimsSetType;
+            return this;
+        }
+
+        /**
+         * Sets the JWT signature.
+         *
+         * @param signature
+         * @return this builder instance.
+         */
+        public Builder setSignature(String signature) {
+            this.signature = signature;
+            return this;
+        }
+
+        /**
+         * Creates a new {@link JWT} instance.
+         *
+         * @return a new {@link JWT} instance.
+         */
+        public JWT build() {
+            return new JWT(new Header(headerType, headerAlgorithm, headerContentType),
+                           new ClaimsSet(claimsSetIssuer,
+                                         claimsSetSubject,
+                                         claimsSetAudience,
+                                         claimsSetExpirationTime,
+                                         claimsSetNotBefore,
+                                         claimsSetIssuedAt,
+                                         claimsSetJwdId,
+                                         claimsSetType),
+                           signature);
+        }
+
     }
 
 }

Copied: oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtils.java (from
r1480569, oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtil.java)
URL: http://svn.apache.org/viewvc/oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtils.java?p2=oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtils.java&p1=oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtil.java&r1=1480569&r2=1480619&rev=1480619&view=diff
==============================================================================
--- oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtil.java (original)
+++ oltu/trunk/oauth-2.0/jwt/src/main/java/org/apache/oltu/oauth2/jwt/JWTUtils.java Thu May
 9 13:16:12 2013
@@ -16,14 +16,22 @@
  */
 package org.apache.oltu.oauth2.jwt;
 
+import static java.lang.String.format;
+
+import java.io.StringWriter;
 import java.nio.charset.Charset;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
 import org.apache.commons.codec.binary.Base64;
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
 
 /**
  * This class contains utility methods required for the JWT building and
  * processing.
  */
-public class JWTUtil {
+public class JWTUtils {
 
     /**
      * The {@code UTF-8} charset reference.
@@ -33,38 +41,207 @@ public class JWTUtil {
     /**
      * The Base64 JSON string default separator.
      */
-    private static final String DEFAULT_SEPARATOR = "\\.";
+    private static final Pattern BASE64_JWT_PATTERN = Pattern.compile("([a-zA-Z0-9/+=]+)\\.([a-zA-Z0-9/+=]+)\\.(.+)");
+
+    // header defined in the JWT specification
+
+    /**
+     * The {@code typ} JWT Header key.
+     */
+    private static final String TYPE = "typ";
+
+    /**
+     * The {@code alg} JWT Header key.
+     */
+    public static final String ALGORITHM = "alg";
+
+    /**
+     * The {@code cty} JWT Header key.
+     */
+    public static final String CONTENT_TYPE = "cty";
+
+    // reserved claims defined in the JWT specification
+
+    /**
+     * The {@code iss} JWT Claims Set key.
+     */
+    private static final String ISSUER = "iss";
+
+    /**
+     * The {@code sub} JWT Claims Set key.
+     */
+    private static final String SUBJECT = "sub";
+
+    /**
+     * The {@code aud} JWT Claims Set key.
+     */
+    private static final String AUDIENCE = "aud";
+
+    /**
+     * The {@code exp} JWT Claims Set key.
+     */
+    private static final String EXPIRATION_TIME = "exp";
+
+    /**
+     * The {@code nbf} JWT Claims Set key.
+     */
+    private static final String NOT_BEFORE = "nbf";
+
+    /**
+     * The {@code iat} JWT Claims Set key.
+     */
+    private static final String ISSUED_AT = "iat";
+
+    /**
+     * The {@code jti} JWT Claims Set key.
+     */
+    private static final String JWT_ID = "jti";
 
     /**
      * Hidden constructor, this class must not be instantiated.
      */
-    private JWTUtil() {
+    private JWTUtils() {
         // do nothing
     }
 
+    // parse
+
+    /**
+     * Parses a Base64 encoded JSON Web Token.
+     *
+     * @param base64jsonString a Base64 encoded JSON Web Token.
+     * @return a JWT instance.
+     */
+    public static JWT parseJWT(String base64jsonString) {
+        if (base64jsonString == null || base64jsonString.isEmpty()) {
+            throw new IllegalArgumentException("Impossible to obtain a JWT from a null or
empty string");
+        }
+
+        Matcher matcher = BASE64_JWT_PATTERN.matcher(base64jsonString);
+        if (!matcher.matches()) {
+            throw new IllegalArgumentException(base64jsonString
+                                               + "is not avalid JSON Web Token, it does not
match with the pattern: "
+                                               + BASE64_JWT_PATTERN.pattern());
+        }
+
+        JSONObject headerObject = decodeJSON(matcher.group(1));
+        JSONObject claimsSetObject = decodeJSON(matcher.group(2));
+        String signature = matcher.group(3);
+
+        return new JWT.Builder()
+                      .setHeaderAlgorithm(getString(headerObject, ALGORITHM))
+                      .setHeaderContentType(getString(headerObject, CONTENT_TYPE))
+                      .setHeaderType(getString(headerObject, CONTENT_TYPE))
+                      .setClaimsSetAudience(getString(claimsSetObject, AUDIENCE))
+                      .setClaimsSetExpirationTime(getLong(claimsSetObject, EXPIRATION_TIME))
+                      .setClaimsSetIssuedAt(getLong(claimsSetObject, ISSUED_AT))
+                      .setClaimsSetIssuer(getString(claimsSetObject, ISSUER))
+                      .setClaimsSetJwdId(getString(claimsSetObject, JWT_ID))
+                      .setClaimsSetNotBefore(getString(claimsSetObject, NOT_BEFORE))
+                      .setClaimsSetSubject(getString(claimsSetObject, SUBJECT))
+                      .setClaimsSetType(getString(claimsSetObject, TYPE))
+                      .setSignature(signature)
+                      .build();
+    }
+
+    private static JSONObject decodeJSON(String base64jsonString) {
+        String decodedJsonString = new String(new Base64(true).decode(base64jsonString),
UTF_8);
+
+        try {
+            return new JSONObject(decodedJsonString);
+        } catch (JSONException e) {
+            throw new IllegalArgumentException(format("BASE64 string '%s' (decoded to '%s')
is not a valid JSON object representation",
+                                                      base64jsonString, decodedJsonString));
+        }
+    }
+
+    private static String getString(JSONObject object, String key) {
+        try {
+            return object.getString(key);
+        } catch (JSONException e) {
+            return null;
+        }
+    }
+
+    private static long getLong(JSONObject object, String key) {
+        try {
+            return object.getLong(key);
+        } catch (JSONException e) {
+            return 0;
+        }
+    }
+
+    // serialization
+
     /**
-     * Get the Header as defined in the 6.1 section of the JWT
-     * specification (http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-6.1)
+     * Serializes the input JWT Header to its correct JSON representation.
      *
-     * @param base64jsonString
-     * @return the decoded JWT header
+     * @param header the JWT Header has to be serialized.
+     * @return the JSON string that represents the JWT Header.
      */
-    public static String getHeader(String base64jsonString){
-        return decodeJSON(base64jsonString.split(DEFAULT_SEPARATOR)[0]);
+    public static String toJson(Header header) {
+        if (header == null) {
+            throw new IllegalArgumentException("Null JWT Header cannot be serialized to JSON
representation.");
+        }
+
+        JSONObject object = new JSONObject();
+        setString(object, ALGORITHM, header.getAlgorithm());
+        setString(object, CONTENT_TYPE, header.getContentType());
+        setString(object, TYPE, header.getType());
+        return toJson(object);
     }
 
     /**
-     * Get the Claims Set as defined in the 6.1 section of the JWT
-     * specification (http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-6.1)
+     * Serializes the input JWT Claims Set to its correct JSON representation.
      *
-     * @param base64jsonString
-     * @return the decoded JWT claim set
+     * @param claimsSet the JWT Claims Set has to be serialized.
+     * @return the JSON string that represents the JWT Claims Set.
      */
-    public static String getClaimsSet(String base64jsonString){
-        return decodeJSON(base64jsonString.split(DEFAULT_SEPARATOR)[1]);
+    public static String toJson(ClaimsSet claimsSet) {
+        if (claimsSet == null) {
+            throw new IllegalArgumentException("Null JWT Claims Set cannot be serialized
to JSON representation.");
+        }
+
+        JSONObject object = new JSONObject();
+        setString(object, AUDIENCE, claimsSet.getAudience());
+        setString(object, ISSUER, claimsSet.getIssuer());
+        setString(object, JWT_ID, claimsSet.getJwdId());
+        setString(object, NOT_BEFORE, claimsSet.getNotBefore());
+        setString(object, SUBJECT, claimsSet.getSubject());
+        setString(object, TYPE, claimsSet.getType());
+        setLong(object, EXPIRATION_TIME, claimsSet.getExpirationTime());
+        setLong(object, ISSUED_AT, claimsSet.getIssuedAt());
+        return toJson(object);
+    }
+
+    private static String toJson(JSONObject object) {
+        StringWriter writer = new StringWriter();
+        try {
+            object.write(writer);
+        } catch (JSONException e) {
+            // swallow it, it should be safe enough to write to a StringWriter
+        }
+        return writer.toString();
     }
 
-    private static String decodeJSON(String base64jsonString){
-        return new String(new Base64(true).decode(base64jsonString), UTF_8);
+    private static void setString(JSONObject object, String key, String value) {
+        if (value != null) {
+            try {
+                object.put(key, value);
+            } catch (JSONException e) {
+                // swallow it, null values are already guarded
+            }
+        }
     }
+
+    private static void setLong(JSONObject object, String key, long value) {
+        if (value != 0) {
+            try {
+                object.put(key, value);
+            } catch (JSONException e) {
+                // swallow it, null values are already guarded
+            }
+        }
+    }
+
 }



Mime
View raw message