Reputation: 49
I'm trying to create a web token using the jjwt library, but I can't figure out how to send an object as one of the claims. If I parse the object or manually create the string the entire string is coming through as the value instead of a separate JSON object. For instance, I want to send something that looks like this:
{
"iss": "NQoFK1NLVelFWOBQtQ8A",
"iat": 1511963669,
"user": {
"id": "exampleuser",
"email": "[email protected]",
"name": "A User",
}
}
But all I've been able to create is:
{
"iss": "NQoFK1NLVelFWOBQtQ8A",
"iat": 1511963669,
"user": "{\"id\": \"[email protected]\",\"email\": \"[email protected]\",\"name\": \"A User\"}"
}
Upvotes: 1
Views: 6187
Reputation: 49
Thank you for your answer, that will be a nice feature to have, once it's available. I wanted to follow up and post a workaround that I found, in case it helps anyone else in the meantime. I was able to create the JSON I needed using a Java HashMap (I found out the hard way that a Scala Map does not work) and then passing that as the value of the claim:
val user: util.Map[String, String] = new util.HashMap[String,
String]() user.put("id", email.value) user.put("email", email.value)
user.put("name", name.displayName)
...
val jws: String = Jwts.builder()
.claim("user", user)
.signWith(key).compact()
Upvotes: 2
Reputation: 19547
Welcome to StackOverflow!
This feature will be natively supported by JJWT when using Jackson in the upcoming JJWT 0.11.0 release (and you can read the docs for this feature too). But it is not available natively in 0.10.X and earlier.
Prior to 0.11.0, and assuming you're using Jackson, you'll have to do this yourself manually with the ObjectMapper:
// when creating:
User user = getUser();
ObjectMapper objectMapper = new ObjectMapper(); // or use an existing one
String json = objectMapper.writeValueAsString(user);
byte[] bytes = json.getBytes(StandardCharsets.UTF_8)
String base64 = Encoders.BASE64.encode(bytes);
String jws = Jwts.builder()
...
.claim("userJsonBase64", base64)
...
.compact();
//when parsing:
String userJsonBase64 = Jwts.parser()....parseClaimsJws(jws).getBody().get("userJsonBase64", String.class);
bytes = Decoders.BASE64.decode(userJsonBase64);
json = new String(bytes, StandardCharsets.UTF_8);
user = objectMapper.readValue(json, User.class);
Upvotes: 4