Added addClaims function to JwtBuilder as described in Issue #196.

This function does not overwrite existing claims (as compared to setClaims).
This commit is contained in:
Robert Erdin 2017-01-10 13:22:23 +01:00
parent 5c0cfdc897
commit b250af4149
3 changed files with 39 additions and 8 deletions

View File

@ -101,6 +101,18 @@ public interface JwtBuilder extends ClaimsMutator<JwtBuilder> {
*/
JwtBuilder setClaims(Map<String, Object> claims);
/**
* Adds all given name/value pairs to the JSON Claims in the payload. If a Claims instance does not yet exist at the
* time this method is called, one will be created automatically before applying the name/value pairs.
*
* <p>The payload and claims properties are mutually exclusive - only one of the two may be used.</p>
*
* @param claims the JWT claims to be added to the JWT body.
* @return the builder for method chaining.
* @since 0.8
*/
JwtBuilder addClaims(Map<String, Object> claims);
/**
* Sets the JWT Claims <a href="https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-4.1.1">
* <code>iss</code></a> (issuer) value. A {@code null} value will remove the property from the Claims.

View File

@ -17,14 +17,7 @@ package io.jsonwebtoken.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodec;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.crypto.DefaultJwtSigner;
import io.jsonwebtoken.impl.crypto.JwtSigner;
import io.jsonwebtoken.lang.Assert;
@ -148,6 +141,12 @@ public class DefaultJwtBuilder implements JwtBuilder {
return this;
}
@Override
public JwtBuilder addClaims(Map<String, Object> claims) {
ensureClaims().putAll(claims);
return this;
}
@Override
public JwtBuilder setIssuer(String iss) {
if (Strings.hasText(iss)) {

View File

@ -74,6 +74,26 @@ class DefaultJwtBuilderTest {
assertSame b.claims, c
}
@Test
void testAddClaims() {
def b = new DefaultJwtBuilder()
def c = Jwts.claims([initial: 'initial'])
b.setClaims(c)
def c2 = [foo: 'bar', baz: 'buz']
b.addClaims(c2)
assertEquals 'initial', b.claims.get('initial')
assertEquals 'bar', b.claims.get('foo')
}
@Test
void testAddClaimsWithoutInitializing() {
def b = new DefaultJwtBuilder()
def c = [foo: 'bar', baz: 'buz']
b.addClaims(c)
assertNotNull b.claims
assertEquals b.claims, c
}
@Test
void testClaim() {
def b = new DefaultJwtBuilder()