Ver Fonte

Add OidcIdToken.Builder

Fixes gh-7592
Josh Cummings há 5 anos atrás
pai
commit
c76775159c

+ 217 - 3
oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcIdToken.java

@@ -15,13 +15,29 @@
  */
 package org.springframework.security.oauth2.core.oidc;
 
-import org.springframework.security.oauth2.core.AbstractOAuth2Token;
-import org.springframework.util.Assert;
-
 import java.time.Instant;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.LinkedHashMap;
+import java.util.List;
 import java.util.Map;
+import java.util.function.Consumer;
+
+import org.springframework.security.oauth2.core.AbstractOAuth2Token;
+import org.springframework.util.Assert;
+
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.ACR;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AMR;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AT_HASH;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AUD;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AUTH_TIME;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AZP;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.C_HASH;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.EXP;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.IAT;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.ISS;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.NONCE;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.SUB;
 
 /**
  * An implementation of an {@link AbstractOAuth2Token} representing an OpenID Connect Core 1.0 ID Token.
@@ -59,4 +75,202 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce
 	public Map<String, Object> getClaims() {
 		return this.claims;
 	}
+
+	/**
+	 * Create a {@link Builder} based on the given token value
+	 *
+	 * @param tokenValue the token value to use
+	 * @return the {@link Builder} for further configuration
+	 * @since 5.3
+	 */
+	public static Builder withTokenValue(String tokenValue) {
+		return new Builder(tokenValue);
+	}
+
+	/**
+	 * A builder for {@link OidcIdToken}s
+	 *
+	 * @author Josh Cummings
+	 * @since 5.3
+	 */
+	public static final class Builder {
+		private String tokenValue;
+		private final Map<String, Object> claims = new LinkedHashMap<>();
+
+		private Builder(String tokenValue) {
+			this.tokenValue = tokenValue;
+		}
+
+		/**
+		 * Use this token value in the resulting {@link OidcIdToken}
+		 *
+		 * @param tokenValue The token value to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder tokenValue(String tokenValue) {
+			this.tokenValue = tokenValue;
+			return this;
+		}
+
+		/**
+		 * Use this claim in the resulting {@link OidcIdToken}
+		 *
+		 * @param name The claim name
+		 * @param value The claim value
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder claim(String name, Object value) {
+			this.claims.put(name, value);
+			return this;
+		}
+
+		/**
+		 * Provides access to every {@link #claim(String, Object)}
+		 * declared so far with the possibility to add, replace, or remove.
+		 * @param claimsConsumer the consumer
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
+			claimsConsumer.accept(this.claims);
+			return this;
+		}
+
+		/**
+		 * Use this access token hash in the resulting {@link OidcIdToken}
+		 *
+		 * @param accessTokenHash The access token hash to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder accessTokenHash(String accessTokenHash) {
+			return claim(AT_HASH, accessTokenHash);
+		}
+
+		/**
+		 * Use this audience in the resulting {@link OidcIdToken}
+		 *
+		 * @param audience The audience(s) to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder audience(Collection<String> audience) {
+			return claim(AUD, audience);
+		}
+
+		/**
+		 * Use this authentication {@link Instant} in the resulting {@link OidcIdToken}
+		 *
+		 * @param authenticatedAt The authentication {@link Instant} to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder authTime(Instant authenticatedAt) {
+			return claim(AUTH_TIME, authenticatedAt);
+		}
+
+		/**
+		 * Use this authentication context class reference in the resulting {@link OidcIdToken}
+		 *
+		 * @param authenticationContextClass The authentication context class reference to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder authenticationContextClass(String authenticationContextClass) {
+			return claim(ACR, authenticationContextClass);
+		}
+
+		/**
+		 * Use these authentication methods in the resulting {@link OidcIdToken}
+		 *
+		 * @param authenticationMethods The authentication methods to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder authenticationMethods(List<String> authenticationMethods) {
+			return claim(AMR, authenticationMethods);
+		}
+
+		/**
+		 * Use this authorization code hash in the resulting {@link OidcIdToken}
+		 *
+		 * @param authorizationCodeHash The authorization code hash to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder authorizationCodeHash(String authorizationCodeHash) {
+			return claim(C_HASH, authorizationCodeHash);
+		}
+
+		/**
+		 * Use this authorized party in the resulting {@link OidcIdToken}
+		 *
+		 * @param authorizedParty The authorized party to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder authorizedParty(String authorizedParty) {
+			return claim(AZP, authorizedParty);
+		}
+
+		/**
+		 * Use this expiration in the resulting {@link OidcIdToken}
+		 *
+		 * @param expiresAt The expiration to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder expiresAt(Instant expiresAt) {
+			return this.claim(EXP, expiresAt);
+		}
+
+		/**
+		 * Use this issued-at timestamp in the resulting {@link OidcIdToken}
+		 *
+		 * @param issuedAt The issued-at timestamp to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder issuedAt(Instant issuedAt) {
+			return this.claim(IAT, issuedAt);
+		}
+
+		/**
+		 * Use this issuer in the resulting {@link OidcIdToken}
+		 *
+		 * @param issuer The issuer to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder issuer(String issuer) {
+			return this.claim(ISS, issuer);
+		}
+
+		/**
+		 * Use this nonce in the resulting {@link OidcIdToken}
+		 *
+		 * @param nonce The nonce to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder nonce(String nonce) {
+			return this.claim(NONCE, nonce);
+		}
+
+		/**
+		 * Use this subject in the resulting {@link OidcIdToken}
+		 *
+		 * @param subject The subject to use
+		 * @return the {@link Builder} for further configurations
+		 */
+		public Builder subject(String subject) {
+			return this.claim(SUB, subject);
+		}
+
+		/**
+		 * Build the {@link OidcIdToken}
+		 *
+		 * @return The constructed {@link OidcIdToken}
+		 */
+		public OidcIdToken build() {
+			Instant iat = toInstant(this.claims.get(IAT));
+			Instant exp = toInstant(this.claims.get(EXP));
+			return new OidcIdToken(this.tokenValue, iat, exp, this.claims);
+		}
+
+		private Instant toInstant(Object timestamp) {
+			if (timestamp != null) {
+				Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant");
+			}
+			return (Instant) timestamp;
+		}
+	}
 }

+ 139 - 0
oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java

@@ -0,0 +1,139 @@
+/*
+ * Copyright 2002-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.security.oauth2.core.oidc;
+
+import java.time.Instant;
+
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.EXP;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.IAT;
+import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.SUB;
+
+/**
+ * Tests for {@link OidcUserInfo}
+ */
+public class OidcIdTokenBuilderTests {
+	@Test
+	public void buildWhenCalledTwiceThenGeneratesTwoOidcIdTokens() {
+		OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token");
+
+		OidcIdToken first = idTokenBuilder
+				.tokenValue("V1")
+				.claim("TEST_CLAIM_1", "C1")
+				.build();
+
+		OidcIdToken second = idTokenBuilder
+				.tokenValue("V2")
+				.claim("TEST_CLAIM_1", "C2")
+				.claim("TEST_CLAIM_2", "C3")
+				.build();
+
+		assertThat(first.getClaims()).hasSize(1);
+		assertThat(first.getClaims().get("TEST_CLAIM_1")).isEqualTo("C1");
+		assertThat(first.getTokenValue()).isEqualTo("V1");
+
+		assertThat(second.getClaims()).hasSize(2);
+		assertThat(second.getClaims().get("TEST_CLAIM_1")).isEqualTo("C2");
+		assertThat(second.getClaims().get("TEST_CLAIM_2")).isEqualTo("C3");
+		assertThat(second.getTokenValue()).isEqualTo("V2");
+	}
+
+	@Test
+	public void expiresAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() {
+		OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token");
+
+		Instant now = Instant.now();
+
+		OidcIdToken idToken = idTokenBuilder
+				.expiresAt(now).build();
+		assertThat(idToken.getExpiresAt()).isSameAs(now);
+
+		idToken = idTokenBuilder
+				.expiresAt(now).build();
+		assertThat(idToken.getExpiresAt()).isSameAs(now);
+
+		assertThatCode(() -> idTokenBuilder
+				.claim(EXP, "not an instant").build())
+				.isInstanceOf(IllegalArgumentException.class);
+	}
+
+	@Test
+	public void issuedAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() {
+		OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token");
+
+		Instant now = Instant.now();
+
+		OidcIdToken idToken = idTokenBuilder
+				.issuedAt(now).build();
+		assertThat(idToken.getIssuedAt()).isSameAs(now);
+
+		idToken = idTokenBuilder
+				.issuedAt(now).build();
+		assertThat(idToken.getIssuedAt()).isSameAs(now);
+
+		assertThatCode(() -> idTokenBuilder
+				.claim(IAT, "not an instant").build())
+				.isInstanceOf(IllegalArgumentException.class);
+	}
+
+	@Test
+	public void subjectWhenUsingGenericOrNamedClaimMethodThenLastOneWins() {
+		OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token");
+
+		String generic = new String("sub");
+		String named = new String("sub");
+
+		OidcIdToken idToken = idTokenBuilder
+				.subject(named)
+				.claim(SUB, generic).build();
+		assertThat(idToken.getSubject()).isSameAs(generic);
+
+		idToken = idTokenBuilder
+				.claim(SUB, generic)
+				.subject(named).build();
+		assertThat(idToken.getSubject()).isSameAs(named);
+	}
+
+	@Test
+	public void claimsWhenRemovingAClaimThenIsNotPresent() {
+		OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token")
+				.claim("needs", "a claim");
+
+		OidcIdToken idToken = idTokenBuilder
+				.subject("sub")
+				.claims(claims -> claims.remove(SUB))
+				.build();
+		assertThat(idToken.getSubject()).isNull();
+	}
+
+	@Test
+	public void claimsWhenAddingAClaimThenIsPresent() {
+		OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token");
+
+		String name = new String("name");
+		String value = new String("value");
+		OidcIdToken idToken = idTokenBuilder
+				.claims(claims -> claims.put(name, value))
+				.build();
+
+		assertThat(idToken.getClaims()).hasSize(1);
+		assertThat(idToken.getClaims().get(name)).isSameAs(value);
+	}
+}