1 package com.atlassian.asap.api;
2
3 import org.apache.commons.lang3.SerializationUtils;
4 import org.junit.Test;
5
6 import javax.json.Json;
7 import javax.json.JsonObject;
8 import java.io.Serializable;
9 import java.time.Instant;
10 import java.util.Optional;
11
12 import static org.hamcrest.Matchers.contains;
13 import static org.hamcrest.Matchers.equalTo;
14 import static org.hamcrest.Matchers.instanceOf;
15 import static org.hamcrest.Matchers.is;
16 import static org.hamcrest.Matchers.not;
17 import static org.junit.Assert.assertThat;
18
19 public class JwtBuilderTest {
20 public static final Jwt SOME_JWT = JwtBuilder.newJwt()
21 .keyId("keyId").issuer("issuer").audience("audience")
22 .issuedAt(Instant.EPOCH)
23 .build();
24
25 @Test
26 public void shouldCreateIdenticalCopyOfPrototype() {
27 Jwt jwtCopy = JwtBuilder.copyJwt(SOME_JWT).build();
28 assertThat(jwtCopy, equalTo(SOME_JWT));
29 }
30
31 @Test
32 public void shouldCreateFreshTokenFromPrototype() {
33 Jwt freshJwt = JwtBuilder.newFromPrototype(SOME_JWT).build();
34
35
36 assertThat(freshJwt.getClaims().getJwtId(), not(equalTo(SOME_JWT.getClaims().getJwtId())));
37 assertThat(freshJwt.getClaims().getIssuedAt(), not(equalTo(SOME_JWT.getClaims().getIssuedAt())));
38
39
40 assertThat(freshJwt.getHeader().getKeyId(), is("keyId"));
41 assertThat(freshJwt.getClaims().getIssuer(), is("issuer"));
42 assertThat(freshJwt.getClaims().getAudience(), contains("audience"));
43 }
44
45 @Test
46 public void shouldReturnSerializableJwt() {
47 assertThat(SOME_JWT, instanceOf(Serializable.class));
48
49 byte[] serializedJwt = SerializationUtils.serialize((Serializable) SOME_JWT);
50 Object deserializedObject = SerializationUtils.deserialize(serializedJwt);
51 assertThat(deserializedObject, equalTo(SOME_JWT));
52 }
53
54 @Test
55 public void customClaimsCanBeIncluded() {
56 JsonObject customClaims = Json.createObjectBuilder()
57 .add("wizard", "harry")
58 .add("number", 42)
59 .build();
60 Jwt jwt = JwtBuilder.copyJwt(SOME_JWT)
61 .customClaims(customClaims)
62 .build();
63 JsonObject json = jwt.getClaims().getJson();
64 assertThat(json.getString("wizard"), is("harry"));
65 assertThat(json.getInt("number"), is(42));
66 }
67
68 @Test
69 public void registeredClaimsTakePrecedenceOverCustomClaims() {
70 JsonObject customClaims = Json.createObjectBuilder()
71 .add("iss", "should-be-ignored")
72 .add("sub", "should-be-ignored")
73 .add("nbf", "should-be-ignored")
74 .build();
75 Jwt jwt = JwtBuilder.copyJwt(SOME_JWT)
76 .issuer("issuer1")
77 .subject(Optional.empty())
78 .notBefore(Optional.empty())
79 .customClaims(customClaims).build();
80
81 assertThat(jwt.getClaims().getIssuer(), is("issuer1"));
82 assertThat(jwt.getClaims().getSubject(), is(Optional.empty()));
83 assertThat(jwt.getClaims().getNotBefore(), is(Optional.empty()));
84 }
85 }