unexpected result from JwtClaims.setClaim(String, javax.json.JsonObject)

Issue #160 closed
Bruce Tiffany created an issue

Greetings,

When adding a JsonObject as a claim value, the resulting JSON producted by JwtClaims.toJson() appears to be incorrect. The recreate is shown below.

// on classpath: jose4j-0.7.0.jar, javax.json-1.1.4.jar

import javax.json.Json;
import javax.json.JsonObject;

import org.jose4j.jwt.JwtClaims;

public class Testit {
  public static void main(String[] args) {
      JsonObject jo1 = Json.createObjectBuilder().add("height", "tall").add("weight", "average").add("eyecolor","brown").build();

      JwtClaims claims = new JwtClaims();
      claims.setClaim("userdata", jo1);
      System.out.println(claims.toJson());
      // produces: {"userdata":{"height":"\"tall\"","weight":"\"average\"","eyecolor":"\"brown\""}}
      // expected: {"userdata":{"height":"tall","weight":"average","eyecolor":"brown"}}

  }
}

Comments (4)

  1. Brian Campbell repo owner

    Long ago, jose4j's internal JSON processing was derived from the JSON.simple toolkit. It is fairly basic in how it converts between JSON and Java objects. It will do strings, numbers, booleans, maps and lists.

    When it sees something it doesn’t recognize when serializing to JSON, it will call toString on it and treat it as a string. However JsonStringImpl's toString quotes and escapes, which then jose4j’s JSON processing quotes and escapes again. That’s what you are seeing.

    If you want/need to use a different JSON library like the javax.json stuff, you can use setPayload(...) on JsonWebSignature or JsonWebEncryption and pass it the the full JSON content from the JsonObject/JsonObjectBuilder.

    And when consuming a JWT, getRawJson on JwtClaims will give you the JSON string payload that you can hand off to a javax.json.JsonReader.

  2. Brian Campbell repo owner

    Or you could just not use the javax.json stuff and pass a map to the JwtClaims object:

    Map<String, Object> userdata = new HashMap<>();
    userdata.put("height", "tall");
    userdata.put("weight", "average");
    userdata.put("eyecolor","brown");
    
    JwtClaims claims = new JwtClaims();
    claims.setClaim("userdata", userdata);
    System.out.println(claims.toJson())
    

    will give {"userdata":{"weight":"average","eyecolor":"brown","height":"tall"}}

  3. Log in to comment