Skip to content

Commit 3f37172

Browse files
authored
feat: add JwtCredentials with custom claims (#290)
* Implement JwtCredentials class. Switch cache to index by claims * DI clock and lifeSpanSeconds * Adding Serializable and adding test * Lock for JwtCredentials * Add tests for verifying access tokens and withClaims * Add tests for withClaims for ServiceAccountJwtAccessCredentials * Fix dependency issues * Add CLOCK_SKEW (5 minutes) for shouldRefresh() * Adding some javadocs * withClaims -> jwtWithClaims and create JwtProvider interface * Fix javadoc * Address some PR review nits * expiry -> expiryInSeconds * Disallow null values in JwtCredentials.Builder * Update license header for the added files * Address PR review comments * Remove extra whitespace * Fix lint * Refactor JwtCredentials.Claims -> JwtClaims * fix formatting * javadocs 'New claims' -> 'new claims'
1 parent de79e14 commit 3f37172

10 files changed

+903
-52
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/*
2+
* Copyright 2019, Google LLC
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions are
6+
* met:
7+
*
8+
* * Redistributions of source code must retain the above copyright
9+
* notice, this list of conditions and the following disclaimer.
10+
* * Redistributions in binary form must reproduce the above
11+
* copyright notice, this list of conditions and the following disclaimer
12+
* in the documentation and/or other materials provided with the
13+
* distribution.
14+
*
15+
* * Neither the name of Google LLC nor the names of its
16+
* contributors may be used to endorse or promote products derived from
17+
* this software without specific prior written permission.
18+
*
19+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20+
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21+
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22+
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23+
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24+
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25+
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26+
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27+
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30+
*/
31+
32+
package com.google.auth.oauth2;
33+
34+
import com.google.auto.value.AutoValue;
35+
import java.io.Serializable;
36+
import javax.annotation.Nullable;
37+
38+
/**
39+
* Value class representing the set of fields used as the payload of a JWT token.
40+
*
41+
* <p>To create and customize claims, use the builder:
42+
*
43+
* <pre><code>
44+
* Claims claims = Claims.newBuilder()
45+
* .setAudience("https://example.com/some-audience")
46+
* .setIssuer("[email protected]")
47+
* .setSubject("[email protected]")
48+
* .build();
49+
* </code></pre>
50+
*/
51+
@AutoValue
52+
public abstract class JwtClaims implements Serializable {
53+
private static final long serialVersionUID = 4974444151019426702L;
54+
55+
@Nullable
56+
abstract String getAudience();
57+
58+
@Nullable
59+
abstract String getIssuer();
60+
61+
@Nullable
62+
abstract String getSubject();
63+
64+
static Builder newBuilder() {
65+
return new AutoValue_JwtClaims.Builder();
66+
}
67+
68+
/**
69+
* Returns a new Claims instance with overridden fields.
70+
*
71+
* <p>Any non-null field will overwrite the value from the original claims instance.
72+
*
73+
* @param other claims to override
74+
* @return new claims
75+
*/
76+
public JwtClaims merge(JwtClaims other) {
77+
return newBuilder()
78+
.setAudience(other.getAudience() == null ? getAudience() : other.getAudience())
79+
.setIssuer(other.getIssuer() == null ? getIssuer() : other.getIssuer())
80+
.setSubject(other.getSubject() == null ? getSubject() : other.getSubject())
81+
.build();
82+
}
83+
84+
/**
85+
* Returns whether or not this set of claims is complete.
86+
*
87+
* <p>Audience, issuer, and subject are required to be set in order to use the claim set for a JWT
88+
* token. An incomplete Claims instance is useful for overriding claims when using {@link
89+
* ServiceAccountJwtAccessCredentials#jwtWithClaims(JwtClaims)} or {@link
90+
* JwtCredentials#jwtWithClaims(JwtClaims)}.
91+
*
92+
* @return
93+
*/
94+
public boolean isComplete() {
95+
return getAudience() != null && getIssuer() != null && getSubject() != null;
96+
}
97+
98+
@AutoValue.Builder
99+
abstract static class Builder {
100+
abstract Builder setAudience(String audience);
101+
102+
abstract Builder setIssuer(String issuer);
103+
104+
abstract Builder setSubject(String subject);
105+
106+
abstract JwtClaims build();
107+
}
108+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
/*
2+
* Copyright 2019, Google LLC
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions are
6+
* met:
7+
*
8+
* * Redistributions of source code must retain the above copyright
9+
* notice, this list of conditions and the following disclaimer.
10+
* * Redistributions in binary form must reproduce the above
11+
* copyright notice, this list of conditions and the following disclaimer
12+
* in the documentation and/or other materials provided with the
13+
* distribution.
14+
*
15+
* * Neither the name of Google LLC nor the names of its
16+
* contributors may be used to endorse or promote products derived from
17+
* this software without specific prior written permission.
18+
*
19+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20+
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21+
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22+
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23+
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24+
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25+
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26+
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27+
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30+
*/
31+
32+
package com.google.auth.oauth2;
33+
34+
import com.google.api.client.json.webtoken.JsonWebSignature;
35+
import com.google.api.client.json.webtoken.JsonWebToken;
36+
import com.google.api.client.util.Clock;
37+
import com.google.auth.Credentials;
38+
import com.google.auth.http.AuthHttpConstants;
39+
import com.google.common.annotations.VisibleForTesting;
40+
import com.google.common.base.Preconditions;
41+
import java.io.IOException;
42+
import java.net.URI;
43+
import java.security.GeneralSecurityException;
44+
import java.security.PrivateKey;
45+
import java.util.Collections;
46+
import java.util.List;
47+
import java.util.Map;
48+
import java.util.Objects;
49+
import java.util.concurrent.TimeUnit;
50+
51+
/**
52+
* Credentials class for calling Google APIs using a JWT with custom claims.
53+
*
54+
* <p>Uses a JSON Web Token (JWT) directly in the request metadata to provide authorization.
55+
*
56+
* <pre><code>
57+
* JwtClaims claims = JwtClaims.newBuilder()
58+
* .setAudience("https://example.com/some-audience")
59+
* .setIssuer("[email protected]")
60+
* .setSubject("[email protected]")
61+
* .build();
62+
* Credentials = JwtCredentials.newBuilder()
63+
* .setPrivateKey(privateKey)
64+
* .setPrivateKeyId("private-key-id")
65+
* .setJwtClaims(claims)
66+
* .build();
67+
* </code></pre>
68+
*/
69+
public class JwtCredentials extends Credentials implements JwtProvider {
70+
private static final String JWT_ACCESS_PREFIX = OAuth2Utils.BEARER_PREFIX;
71+
private static final String JWT_INCOMPLETE_ERROR_MESSAGE =
72+
"JWT claims must contain audience, " + "issuer, and subject.";
73+
private static final long CLOCK_SKEW = TimeUnit.MINUTES.toSeconds(5);
74+
75+
// byte[] is serializable, so the lock variable can be final
76+
private final Object lock = new byte[0];
77+
private final PrivateKey privateKey;
78+
private final String privateKeyId;
79+
private final JwtClaims jwtClaims;
80+
private final Long lifeSpanSeconds;
81+
@VisibleForTesting transient Clock clock;
82+
83+
private transient String jwt;
84+
// The date (represented as seconds since the epoch) that the generated JWT expires
85+
private transient Long expiryInSeconds;
86+
87+
private JwtCredentials(Builder builder) {
88+
this.privateKey = Preconditions.checkNotNull(builder.getPrivateKey());
89+
this.privateKeyId = Preconditions.checkNotNull(builder.getPrivateKeyId());
90+
this.jwtClaims = Preconditions.checkNotNull(builder.getJwtClaims());
91+
Preconditions.checkState(jwtClaims.isComplete(), JWT_INCOMPLETE_ERROR_MESSAGE);
92+
this.lifeSpanSeconds = Preconditions.checkNotNull(builder.getLifeSpanSeconds());
93+
this.clock = Preconditions.checkNotNull(builder.getClock());
94+
}
95+
96+
public static Builder newBuilder() {
97+
return new Builder();
98+
}
99+
100+
/** Refresh the token by discarding the cached token and metadata and rebuilding a new one. */
101+
@Override
102+
public void refresh() throws IOException {
103+
JsonWebSignature.Header header = new JsonWebSignature.Header();
104+
header.setAlgorithm("RS256");
105+
header.setType("JWT");
106+
header.setKeyId(privateKeyId);
107+
108+
JsonWebToken.Payload payload = new JsonWebToken.Payload();
109+
payload.setAudience(jwtClaims.getAudience());
110+
payload.setIssuer(jwtClaims.getIssuer());
111+
payload.setSubject(jwtClaims.getSubject());
112+
113+
long currentTime = clock.currentTimeMillis();
114+
payload.setIssuedAtTimeSeconds(currentTime / 1000);
115+
payload.setExpirationTimeSeconds(currentTime / 1000 + lifeSpanSeconds);
116+
117+
synchronized (lock) {
118+
this.expiryInSeconds = payload.getExpirationTimeSeconds();
119+
120+
try {
121+
this.jwt =
122+
JsonWebSignature.signUsingRsaSha256(
123+
privateKey, OAuth2Utils.JSON_FACTORY, header, payload);
124+
} catch (GeneralSecurityException e) {
125+
throw new IOException(
126+
"Error signing service account JWT access header with private key.", e);
127+
}
128+
}
129+
}
130+
131+
private boolean shouldRefresh() {
132+
return expiryInSeconds == null
133+
|| getClock().currentTimeMillis() / 1000 > expiryInSeconds - CLOCK_SKEW;
134+
}
135+
136+
/**
137+
* Returns a copy of these credentials with modified claims.
138+
*
139+
* @param newClaims new claims. Any unspecified claim fields default to the the current values.
140+
* @return new credentials
141+
*/
142+
@Override
143+
public JwtCredentials jwtWithClaims(JwtClaims newClaims) {
144+
return JwtCredentials.newBuilder()
145+
.setPrivateKey(privateKey)
146+
.setPrivateKeyId(privateKeyId)
147+
.setJwtClaims(jwtClaims.merge(newClaims))
148+
.build();
149+
}
150+
151+
@Override
152+
public String getAuthenticationType() {
153+
return "JWT";
154+
}
155+
156+
@Override
157+
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
158+
synchronized (lock) {
159+
if (shouldRefresh()) {
160+
refresh();
161+
}
162+
List<String> newAuthorizationHeaders = Collections.singletonList(JWT_ACCESS_PREFIX + jwt);
163+
return Collections.singletonMap(AuthHttpConstants.AUTHORIZATION, newAuthorizationHeaders);
164+
}
165+
}
166+
167+
@Override
168+
public boolean hasRequestMetadata() {
169+
return true;
170+
}
171+
172+
@Override
173+
public boolean hasRequestMetadataOnly() {
174+
return true;
175+
}
176+
177+
@Override
178+
public boolean equals(Object obj) {
179+
if (!(obj instanceof JwtCredentials)) {
180+
return false;
181+
}
182+
JwtCredentials other = (JwtCredentials) obj;
183+
return Objects.equals(this.privateKey, other.privateKey)
184+
&& Objects.equals(this.privateKeyId, other.privateKeyId)
185+
&& Objects.equals(this.jwtClaims, other.jwtClaims)
186+
&& Objects.equals(this.lifeSpanSeconds, other.lifeSpanSeconds);
187+
}
188+
189+
@Override
190+
public int hashCode() {
191+
return Objects.hash(this.privateKey, this.privateKeyId, this.jwtClaims, this.lifeSpanSeconds);
192+
}
193+
194+
Clock getClock() {
195+
if (clock == null) {
196+
clock = Clock.SYSTEM;
197+
}
198+
return clock;
199+
}
200+
201+
public static class Builder {
202+
private PrivateKey privateKey;
203+
private String privateKeyId;
204+
private JwtClaims jwtClaims;
205+
private Clock clock = Clock.SYSTEM;
206+
private Long lifeSpanSeconds = TimeUnit.HOURS.toSeconds(1);
207+
208+
protected Builder() {}
209+
210+
public Builder setPrivateKey(PrivateKey privateKey) {
211+
this.privateKey = Preconditions.checkNotNull(privateKey);
212+
return this;
213+
}
214+
215+
public PrivateKey getPrivateKey() {
216+
return privateKey;
217+
}
218+
219+
public Builder setPrivateKeyId(String privateKeyId) {
220+
this.privateKeyId = Preconditions.checkNotNull(privateKeyId);
221+
return this;
222+
}
223+
224+
public String getPrivateKeyId() {
225+
return privateKeyId;
226+
}
227+
228+
public Builder setJwtClaims(JwtClaims claims) {
229+
this.jwtClaims = Preconditions.checkNotNull(claims);
230+
return this;
231+
}
232+
233+
public JwtClaims getJwtClaims() {
234+
return jwtClaims;
235+
}
236+
237+
public Builder setLifeSpanSeconds(Long lifeSpanSeconds) {
238+
this.lifeSpanSeconds = Preconditions.checkNotNull(lifeSpanSeconds);
239+
return this;
240+
}
241+
242+
public Long getLifeSpanSeconds() {
243+
return lifeSpanSeconds;
244+
}
245+
246+
Builder setClock(Clock clock) {
247+
this.clock = Preconditions.checkNotNull(clock);
248+
return this;
249+
}
250+
251+
Clock getClock() {
252+
return clock;
253+
}
254+
255+
public JwtCredentials build() {
256+
return new JwtCredentials(this);
257+
}
258+
}
259+
}

0 commit comments

Comments
 (0)