[java-idp-oidc] branch main updated: JOIDC-201 - Support for OAuth 2.0 Demonstrating Proof of Possession (DPoP)
Henri Mikkonen
henri.mikkonen at iki.fi
Wed May 22 12:30:21 UTC 2024
This is an automated email from the git hooks/post-receive script.
hjmikkon pushed a commit to branch main
in repository java-idp-oidc.
View the commit online:
http://git.shibboleth.net/view/?p=java-idp-oidc.git;a=commit;h=d806e60055bf5884b152ee5bfde81db488dc25ec
The following commit(s) were added to refs/heads/main by this push:
new d806e600 JOIDC-201 - Support for OAuth 2.0 Demonstrating Proof of Possession (DPoP)
d806e600 is described below
commit d806e60055bf5884b152ee5bfde81db488dc25ec
Author: Henri Mikkonen <henri.mikkonen at iki.fi>
AuthorDate: Wed May 22 15:29:45 2024 +0300
JOIDC-201 - Support for OAuth 2.0 Demonstrating Proof of Possession (DPoP)
https://shibboleth.atlassian.net/browse/JOIDC-201
Included nonce management to the DPoP feature.
- dpopProofNonceGenerator setting defaults to DefaultOAuth2DPoPNonceGenerator bean
- It creates a JSON structure with a random 'jti' claim and 'exp' with configurable lifetime (default 5 mins)
- Nonce value contains the JSON, encrypted with a DataSealer
- DPoPSignatureValidationConfiguration contains a claim validator for nonces
- Nonce value is optional if no dpopProofNonceGenerator is set
- Otherwise value needs to a value that can be unwrapped via sealer and has 'exp' in the future
- DPoPProofNonceJWTValidationException is thrown if mandatory nonce is missing or is invalid
- ValidateDPoPProof exploits DPoPProofNonceJWTValidationException and dpopProofNonceGenerator
- The "DPoP-Nonce" header is included in HttpServletResponse
---
.../op/encoding/impl/NimbusResponseEncoder.java | 3 +
.../op/oauth2/profile/impl/ValidateDPoPProof.java | 60 +++++++-
.../claims/impl/DPoPProofNonceClaimsValidator.java | 143 +++++++++++++++++++
.../impl/DPoPProofNonceJWTValidationException.java | 37 +++++
.../impl/DefaultDPoPProofNonceGenerator.java | 154 +++++++++++++++++++++
.../META-INF/net.shibboleth.idp/postconfig.xml | 2 +
.../dpop-proof-validation-beans.xml | 3 +-
.../idp/service/relying-party/postconfig.xml | 32 ++++-
.../op/profile/flow/AbstractOidcApiFlowTest.java | 23 ++-
.../oidc/op/profile/flow/AbstractOidcFlowTest.java | 21 ++-
.../op/profile/flow/PushedAuthorizeFlowTest.java | 18 ++-
.../plugin/oidc/op/profile/flow/TokenFlowTest.java | 54 ++++++--
.../plugin/oidc/op/profile/flow/UserInfoTest.java | 60 ++++++--
13 files changed, 580 insertions(+), 30 deletions(-)
diff --git a/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/encoding/impl/NimbusResponseEncoder.java b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/encoding/impl/NimbusResponseEncoder.java
index eb0fe77c..0d5bcbdf 100644
--- a/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/encoding/impl/NimbusResponseEncoder.java
+++ b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/encoding/impl/NimbusResponseEncoder.java
@@ -199,6 +199,9 @@ public class NimbusResponseEncoder extends AbstractHttpServletResponseMessageEnc
return;
}
final HTTPResponse resp = ((Response) message).toHTTPResponse();
+ for (final String header : response.getHeaderNames()) {
+ resp.setHeader(header, response.getHeader(header));
+ }
getProtocolMessageLogger().trace("Outbound response {}", ResponseUtil.toString(resp, objectMapper));
JakartaServletUtils.applyHTTPResponse(resp, response);
} catch (final IOException e) {
diff --git a/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/oauth2/profile/impl/ValidateDPoPProof.java b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/oauth2/profile/impl/ValidateDPoPProof.java
index 6475e947..c4a5893f 100644
--- a/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/oauth2/profile/impl/ValidateDPoPProof.java
+++ b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/oauth2/profile/impl/ValidateDPoPProof.java
@@ -33,11 +33,15 @@ import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.oauth2.sdk.Request;
+import jakarta.servlet.http.HttpServletResponse;
import net.shibboleth.idp.plugin.oidc.op.oauth2.messaging.context.OAuth2DPoPProofContext;
import net.shibboleth.idp.plugin.oidc.op.profile.impl.AbstractOIDCRequestAction;
+import net.shibboleth.idp.plugin.oidc.op.security.jwt.claims.impl.DPoPProofNonceJWTValidationException;
+import net.shibboleth.idp.profile.IdPEventIds;
import net.shibboleth.oidc.jwt.claims.ClaimsValidator;
import net.shibboleth.oidc.jwt.claims.JWTValidationException;
import net.shibboleth.oidc.profile.config.navigate.DPoPProofClaimsValidatorLookupFunction;
+import net.shibboleth.oidc.profile.config.navigate.DPoPProofNonceGeneratorLookupFunction;
import net.shibboleth.oidc.profile.core.OidcEventIds;
import net.shibboleth.shared.logic.Constraint;
import net.shibboleth.shared.primitive.LoggerFactory;
@@ -54,6 +58,10 @@ public class ValidateDPoPProof extends AbstractOIDCRequestAction<Request> {
/** Lookup for the claims validator to be applied for validating the DPoP proof. */
@Nonnull private Function<ProfileRequestContext, ClaimsValidator> claimsValidatorLookupStrategy;
+ /** Lookup for the nonce generator used for generating nonces. */
+ @Nonnull private Function<ProfileRequestContext, Function<ProfileRequestContext, String>>
+ nonceGeneratorLookupStrategy;
+
/** The claims validator to be applied for validating the DPoP proof. */
@Nullable private ClaimsValidator claimsValidator;
@@ -62,6 +70,7 @@ public class ValidateDPoPProof extends AbstractOIDCRequestAction<Request> {
*/
public ValidateDPoPProof() {
claimsValidatorLookupStrategy = new DPoPProofClaimsValidatorLookupFunction();
+ nonceGeneratorLookupStrategy = new DPoPProofNonceGeneratorLookupFunction();
}
/**
* Set the lookup strategy for the claims validator used for validating the DPoP proof.
@@ -74,6 +83,16 @@ public class ValidateDPoPProof extends AbstractOIDCRequestAction<Request> {
claimsValidatorLookupStrategy = Constraint.isNotNull(strategy, "Lookup strategy cannot be null");
}
+ /**
+ * Set the lookup strategy for the nonce generator to create nonces to be used in DPoP proof.
+ *
+ * @param strategy What to set
+ */
+ public void setDpopProofNonceGeneratorLookupStrategy(
+ @Nonnull final Function<ProfileRequestContext,Function<ProfileRequestContext,String>> strategy) {
+ nonceGeneratorLookupStrategy = Constraint.isNotNull(strategy, "Lookup strategy cannot be null");
+ }
+
/** {@inheritDoc} */
@Override
protected boolean doPreExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
@@ -131,13 +150,17 @@ public class ValidateDPoPProof extends AbstractOIDCRequestAction<Request> {
if (jwk.isPrivate()) {
log.warn("{} Private key exists in 'jwk' parameter value {}", getLogPrefix(), header.getType());
ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_DPOP_PROOF);
- return;
+ return;
}
-
+
assert jwtClaimsSet != null;
try {
assert claimsValidator != null;
claimsValidator.validate(jwtClaimsSet, profileRequestContext);
+ } catch (final DPoPProofNonceJWTValidationException e) {
+ log.debug("{} DPoP Proof JWT nonce validation failed {}", getLogPrefix(), e.getMessage());
+ handleNonceValidationFailure(profileRequestContext);
+ return;
} catch (final JWTValidationException e) {
log.warn("{} DPoP Proof JWT validation failed: {}", getLogPrefix(), e.getMessage());
ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_DPOP_PROOF);
@@ -154,5 +177,36 @@ public class ValidateDPoPProof extends AbstractOIDCRequestAction<Request> {
}
proofContext.setValidatedDpopProofThumbprint(jwkThumbprint);
log.trace("{} JWK thumbprint stored in the context", getLogPrefix());
- }
+ }
+
+ /**
+ * Attach a new nonce to the HTTP servlet response or builds the corresponding event ID to the given PRC if the
+ * nonce cannot be generated or attached.
+ *
+ * @param profileRequestContext the context to be populated with error event ID
+ */
+ protected void handleNonceValidationFailure(@Nonnull final ProfileRequestContext profileRequestContext) {
+ final Function<ProfileRequestContext, String> nonceGenerator =
+ nonceGeneratorLookupStrategy.apply(profileRequestContext);
+ if (nonceGenerator == null) {
+ log.error("{} Could not fetch nonce generator", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, IdPEventIds.INVALID_PROFILE_CONFIG);
+ return;
+ }
+ final String nonce = nonceGenerator.apply(profileRequestContext);
+ if (nonce == null) {
+ log.error("{} Could not create new nonce via generator", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, IdPEventIds.INVALID_PROFILE_CONFIG);
+ return;
+ }
+ final HttpServletResponse servletResponse = getHttpServletResponse();
+ if (servletResponse == null) {
+ log.error("{} Could not fetch HttpServletResponse", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, IdPEventIds.INVALID_PROFILE_CONFIG);
+ } else {
+ servletResponse.addHeader("DPoP-Nonce", nonce);
+ log.debug("{} DPoP-Nonce header {} added to the response", getLogPrefix(), nonce);
+ ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_DPOP_NONCE);
+ }
+ }
}
\ No newline at end of file
diff --git a/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DPoPProofNonceClaimsValidator.java b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DPoPProofNonceClaimsValidator.java
new file mode 100644
index 00000000..c97179e5
--- /dev/null
+++ b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DPoPProofNonceClaimsValidator.java
@@ -0,0 +1,143 @@
+/*
+ * 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
+ *
+ * http://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 net.shibboleth.idp.plugin.oidc.op.security.jwt.claims.impl;
+
+import java.text.ParseException;
+import java.time.Instant;
+import java.util.Map;
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.slf4j.Logger;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.MapType;
+import com.nimbusds.jwt.JWTClaimsSet;
+
+
+import net.shibboleth.oidc.jwt.claims.AbstractClaimsValidator;
+import net.shibboleth.oidc.jwt.claims.ClaimsValidator;
+import net.shibboleth.oidc.profile.config.navigate.DPoPProofNonceGeneratorLookupFunction;
+import net.shibboleth.shared.annotation.ParameterName;
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.shared.annotation.constraint.ThreadSafeAfterInit;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.security.DataSealer;
+import net.shibboleth.shared.security.DataSealerException;
+
+/**
+ * A {@link ClaimsValidator} for validating if nonce included in the DPoP Proof JWT is valid. The claim is considered
+ * as optional if {@link #nonceGeneratorLookupStrategy} returns null. The values are expected to contain an opaque
+ * value that can be unwrapped with the configurable data sealer. The value needs to have an 'exp' claim with an epoch
+ * vaue in the future.
+ *
+ * In case of missing / invalid nonce, a {@link DPoPProofNonceJWTValidationException} is thrown.
+ */
+ at ThreadSafeAfterInit
+public class DPoPProofNonceClaimsValidator extends AbstractClaimsValidator {
+
+ /** Class logger. */
+ @Nonnull
+ private final Logger log = LoggerFactory.getLogger(DPoPProofNonceClaimsValidator.class);
+
+ /** Data sealer for unwrapping opaque nonce value. */
+ @Nonnull private final DataSealer dataSealer;
+
+ /** JSON object mapper used for decoding JSON into Map. */
+ @NonnullAfterInit private ObjectMapper objectMapper;
+
+ /** Lookup for the nonce generator: if non-null value is returned, nonces are required. */
+ @Nonnull private Function<ProfileRequestContext, Function<ProfileRequestContext, String>>
+ nonceGeneratorLookupStrategy;
+
+ /**
+ * Constructor.
+ *
+ * @param sealer data sealer for unwrapping opaque nonce value
+ */
+ public DPoPProofNonceClaimsValidator(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer) {
+ dataSealer = Constraint.isNotNull(sealer, "Data sealer cannot be null");
+ nonceGeneratorLookupStrategy = new DPoPProofNonceGeneratorLookupFunction();
+ }
+
+ /**
+ * Set the JSON {@link ObjectMapper} used for decoding JSON into Map.
+ *
+ * @param mapper object mapper
+ */
+ public void setObjectMapper(@Nonnull final ObjectMapper mapper) {
+ ifInitializedThrowUnmodifiabledComponentException();
+
+ objectMapper = Constraint.isNotNull(mapper, "Object mapper cannot be null");
+ }
+
+ /**
+ * Set the lookup strategy for the nonce generator: if non-null value is returned, nonces are required.
+ *
+ * @param strategy What to set
+ */
+ public void setDpopProofNonceGeneratorLookupStrategy(
+ @Nonnull final Function<ProfileRequestContext,Function<ProfileRequestContext,String>> strategy) {
+ nonceGeneratorLookupStrategy = Constraint.isNotNull(strategy, "Lookup strategy cannot be null");
+ }
+
+ /** {@inheritDoc} */
+ protected void doInitialize() throws ComponentInitializationException {
+ super.doInitialize();
+ if (objectMapper == null) {
+ throw new ComponentInitializationException("Object mapper cannot be null");
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void doValidate(@Nonnull final JWTClaimsSet claims, @Nonnull final ProfileRequestContext context)
+ throws DPoPProofNonceJWTValidationException {
+
+ final boolean requireNonce = nonceGeneratorLookupStrategy.apply(context) != null;
+ try {
+ final String nonce = claims.getStringClaim("nonce");
+ if (nonce == null) {
+ if (requireNonce) {
+ throw new DPoPProofNonceJWTValidationException("Mandatory value is missing");
+ }
+ return;
+ }
+ final String unwrapped = dataSealer.unwrap(nonce);
+ final MapType mapType =
+ objectMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
+ final Map<String, Object> map = objectMapper.readValue(unwrapped, mapType);
+ final Instant nonceExp = Instant.ofEpochMilli(Long.parseLong((String) map.get("exp")));
+ if (Instant.now().isAfter(nonceExp)) {
+ throw new DPoPProofNonceJWTValidationException("Value is expired");
+ }
+ } catch (final DataSealerException e) {
+ log.trace("Could not unwrap the nonce data", e);
+ throw new DPoPProofNonceJWTValidationException("Could not unwrap the nonce data");
+ } catch (final JsonProcessingException e) {
+ log.warn("Could not decode JSON from the unwrapped nonce", e);
+ throw new DPoPProofNonceJWTValidationException("Could not decode JSON from unwrapped nonce");
+ } catch (final ParseException e) {
+ log.trace("Unexpected format for the nonce claim", e);
+ throw new DPoPProofNonceJWTValidationException("Unexpected format for the nonce claim");
+ }
+ }
+
+}
diff --git a/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DPoPProofNonceJWTValidationException.java b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DPoPProofNonceJWTValidationException.java
new file mode 100644
index 00000000..c7e09509
--- /dev/null
+++ b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DPoPProofNonceJWTValidationException.java
@@ -0,0 +1,37 @@
+/*
+ * 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
+ *
+ * http://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 net.shibboleth.idp.plugin.oidc.op.security.jwt.claims.impl;
+
+import javax.annotation.Nullable;
+
+import net.shibboleth.oidc.jwt.claims.JWTValidationException;
+
+/**
+ * A DPoP Proof nonce-specific extension to {@link JWTValidationException}.
+ */
+public class DPoPProofNonceJWTValidationException extends JWTValidationException {
+
+ /** Serial version UID. */
+ private static final long serialVersionUID = -7004882278378892319L;
+
+ /**
+ * Constructor.
+ *
+ * @param message exception message
+ */
+ public DPoPProofNonceJWTValidationException(@Nullable final String message) {
+ super(message);
+ }
+}
diff --git a/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DefaultDPoPProofNonceGenerator.java b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DefaultDPoPProofNonceGenerator.java
new file mode 100644
index 00000000..53e4aed9
--- /dev/null
+++ b/idp-oidc-extension-impl/src/main/java/net/shibboleth/idp/plugin/oidc/op/security/jwt/claims/impl/DefaultDPoPProofNonceGenerator.java
@@ -0,0 +1,154 @@
+/*
+ * 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
+ *
+ * http://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 net.shibboleth.idp.plugin.oidc.op.security.jwt.claims.impl;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Map;
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.slf4j.Logger;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import net.shibboleth.shared.annotation.ParameterName;
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.shared.annotation.constraint.ThreadSafeAfterInit;
+import net.shibboleth.shared.component.AbstractIdentifiableInitializableComponent;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.logic.FunctionSupport;
+import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.security.DataSealer;
+import net.shibboleth.shared.security.DataSealerException;
+import net.shibboleth.shared.security.IdentifierGenerationStrategy;
+import net.shibboleth.shared.security.impl.SecureRandomIdentifierGenerationStrategy;
+
+/**
+ * Default implementation for the function used for generating new DPoP Proof nonces. The values are opaque String
+ * values that contain JSON structures, wrapped with the configurable data sealer. The JSON structure contains a 'jti'
+ * claim generated with a configurable {@link IdentifierGenerationStrategy} and an 'exp' claim calculated with
+ * configurable lifetime.
+ */
+ at ThreadSafeAfterInit
+public class DefaultDPoPProofNonceGenerator extends AbstractIdentifiableInitializableComponent
+ implements Function<ProfileRequestContext, String> {
+
+ /** Class logger. */
+ @Nonnull
+ private final Logger log = LoggerFactory.getLogger(DefaultDPoPProofNonceGenerator.class);
+
+ /** Data sealer for wrapping the JSON into opaque nonce value. */
+ @Nonnull private final DataSealer dataSealer;
+
+ /** JSON object mapper for encoding map into JSON. */
+ @NonnullAfterInit private ObjectMapper objectMapper;
+
+ /** Lookup function to supply identifier generation strategy to use. */
+ @Nonnull private Function<ProfileRequestContext, IdentifierGenerationStrategy> idGeneratorLookupStrategy;
+
+ /** Nonce lifetime. */
+ @Nonnull private Duration nonceLifetime;
+
+ /**
+ *
+ * Constructor.
+ *
+ * @param sealer data sealer for wrapping the JSON into opaque nonce value
+ */
+ public DefaultDPoPProofNonceGenerator(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer) {
+ dataSealer = Constraint.isNotNull(sealer, "Data sealer cannot be null");
+ final Duration fiveMins = Duration.ofMinutes(5);
+ assert fiveMins != null;
+ nonceLifetime = fiveMins;
+ idGeneratorLookupStrategy = FunctionSupport.constant(new SecureRandomIdentifierGenerationStrategy());
+ }
+
+ /**
+ * Set the JSON {@link ObjectMapper} used for encoding map into JSON.
+ *
+ * @param mapper object mapper
+ */
+ public void setObjectMapper(@Nonnull final ObjectMapper mapper) {
+ ifInitializedThrowUnmodifiabledComponentException();
+
+ objectMapper = Constraint.isNotNull(mapper, "Object mapper cannot be null");
+ }
+
+ /**
+ * Set the nonce lifetime.
+ *
+ * @param duration nonce lifetime
+ */
+ public void setNonceLifetime(@Nonnull final Duration duration) {
+ ifInitializedThrowUnmodifiabledComponentException();
+
+ Constraint.isTrue(!duration.isZero() && !duration.isNegative(), "Nonce lifetime must be greater than 0");
+ nonceLifetime = duration;
+ }
+
+ /**
+ * Set the strategy used to locate the {@link IdentifierGenerationStrategy} to use.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setIdentifierGeneratorLookupStrategy(
+ @Nonnull final Function<ProfileRequestContext,IdentifierGenerationStrategy> strategy) {
+ ifInitializedThrowUnmodifiabledComponentException();
+
+ idGeneratorLookupStrategy =
+ Constraint.isNotNull(strategy, "Identifier generation strategy cannot be null");
+ }
+
+ /** {@inheritDoc} */
+ protected void doInitialize() throws ComponentInitializationException {
+ super.doInitialize();
+ if (objectMapper == null) {
+ throw new ComponentInitializationException("Object mapper cannot be null");
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override @Nullable
+ public String apply(@Nullable final ProfileRequestContext profileRequestContext) {
+ final IdentifierGenerationStrategy idGenerator = idGeneratorLookupStrategy.apply(profileRequestContext);
+ if (idGenerator == null) {
+ log.error("Could not resolve idGenerator");
+ return null;
+ }
+ final String id = idGenerator.generateIdentifier(false);
+ final Instant nonceExp = Instant.now().plus(nonceLifetime);
+ final Map<String, Object> map = Map.of("jti", id, "exp", "" + nonceExp.toEpochMilli());
+ try {
+ final String raw = objectMapper.writeValueAsString(map);
+ if (raw != null) {
+ //TODO configure the extra time for data sealer?
+ final String nonce = dataSealer.wrap(raw, nonceExp.plus(Duration.ofMinutes(5)));
+ log.debug("Successfully generated a new nonce {}", nonce);
+ return nonce;
+ }
+ log.error("Could not encode nonce map into a JSON string");
+ } catch (JsonProcessingException | DataSealerException e) {
+ log.error("Could not create a new nonce", e);
+ }
+ return null;
+ }
+
+}
diff --git a/idp-oidc-extension-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml b/idp-oidc-extension-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml
index 92bffb96..db5ed8f8 100644
--- a/idp-oidc-extension-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml
+++ b/idp-oidc-extension-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml
@@ -688,6 +688,8 @@
value="#{T(com.nimbusds.oauth2.sdk.OAuth2Error).INVALID_DPOP_PROOF_CODE}" />
<entry key="#{T(net.shibboleth.oidc.profile.core.OidcEventIds).MISSING_DPOP_PROOF}"
value="#{T(com.nimbusds.oauth2.sdk.OAuth2Error).INVALID_DPOP_PROOF_CODE}" />
+ <entry key="#{T(net.shibboleth.oidc.profile.core.OidcEventIds).INVALID_DPOP_NONCE}"
+ value="#{T(com.nimbusds.oauth2.sdk.OAuth2Error).USE_DPOP_NONCE_CODE}" />
<!-- Missing from Nimbus. -->
<entry key="#{T(net.shibboleth.oidc.profile.core.OidcEventIds).INVALID_TARGET}"
diff --git a/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/oauth2/dpop-proof-validation/dpop-proof-validation-beans.xml b/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/oauth2/dpop-proof-validation/dpop-proof-validation-beans.xml
index 80b9dfe6..f2bcdf26 100644
--- a/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/oauth2/dpop-proof-validation/dpop-proof-validation-beans.xml
+++ b/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/oauth2/dpop-proof-validation/dpop-proof-validation-beans.xml
@@ -95,6 +95,7 @@
</bean>
<bean id="ValidateDPoPProof" class="net.shibboleth.idp.plugin.oidc.op.oauth2.profile.impl.ValidateDPoPProof"
- scope="prototype" />
+ scope="prototype"
+ p:httpServletResponseSupplier-ref="shibboleth.HttpServletResponseSupplier"/>
</beans>
diff --git a/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/service/relying-party/postconfig.xml b/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/service/relying-party/postconfig.xml
index 03a5e6d5..ed8c3fc1 100644
--- a/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/service/relying-party/postconfig.xml
+++ b/idp-oidc-extension-impl/src/main/resources/META-INF/net/shibboleth/idp/service/relying-party/postconfig.xml
@@ -28,7 +28,8 @@
p:issuedClaimsValidator-ref="DefaultUserInfoJWTClaimsValidator"
p:unregisteredClientPolicy="#{getObject('shibboleth.oidc.DefaultUnregisteredClientPolicy')}"
p:dpopProofClaimsValidator-ref="DefaultUserInfoDPoPProofClaimsValidator"
- p:dpopProofSignatureValidationConfiguration-ref="DPoPSignatureValidationConfiguration" />
+ p:dpopProofSignatureValidationConfiguration-ref="DPoPSignatureValidationConfiguration"
+ p:dpopProofNonceGenerator-ref="DefaultOAuth2DPoPNonceGenerator" />
<bean id="OIDC.Registration" parent="AbstractOIDCProfile" lazy-init="true"
class="net.shibboleth.oidc.profile.config.impl.DefaultOIDCDynamicRegistrationConfiguration"
@@ -270,6 +271,11 @@
p:propertyType="#{T(net.shibboleth.oidc.security.jose.SignatureValidationConfiguration)}"
p:defaultValue-ref="DPoPSignatureValidationConfiguration" />
</property>
+ <property name="dpopProofNonceGeneratorLookupStrategy">
+ <bean parent="shibboleth.MDDrivenBeanProperty" p:propertyName="dpopProofNonceGenerator"
+ p:propertyType="#{T(java.util.function.Function)}"
+ p:defaultValue-ref="DefaultOAuth2DPoPNonceGenerator" />
+ </property>
</bean>
<bean id="OIDC.SSO.MDDriven" parent="AbstractMDDrivenOIDCSSOProfile" lazy-init="true"
@@ -429,6 +435,11 @@
p:propertyType="#{T(net.shibboleth.oidc.security.jose.SignatureValidationConfiguration)}"
p:defaultValue-ref="DPoPSignatureValidationConfiguration" />
</property>
+ <property name="dpopProofNonceGeneratorLookupStrategy">
+ <bean parent="shibboleth.MDDrivenBeanProperty" p:propertyName="dpopProofNonceGenerator"
+ p:propertyType="#{T(java.util.function.Function)}"
+ p:defaultValue-ref="DefaultOAuth2DPoPNonceGenerator" />
+ </property>
</bean>
<bean id="OIDC.Registration.MDDriven" parent="AbstractMDDrivenOIDCFlowAwareProfile" lazy-init="true"
@@ -1024,6 +1035,11 @@
p:customObject-ref="shibboleth.HttpServletRequestSupplier"/>
</property>
</bean>
+ <bean id="DPoPProofNonceClaimsValidator"
+ class="net.shibboleth.idp.plugin.oidc.op.security.jwt.claims.impl.DPoPProofNonceClaimsValidator"
+ p:objectMapper-ref="shibboleth.oidc.JSONObjectMapper"
+ c:sealer-ref="DefaultDPoPNonceSealer">
+ </bean>
</util:list>
<bean id="UserInfoDPoPProofClaimsValidators" parent="DPoPProofClaimsValidators"
@@ -1044,4 +1060,18 @@
</property>
</bean>
+ <bean id="DefaultDPoPNonceSealer" lazy-init="true"
+ class="net.shibboleth.shared.security.DataSealer"
+ p:encoder-ref="base64Codec"
+ p:decoder-ref="base64Codec"
+ p:keyStrategy-ref="#{'%{idp.sealer.keyStrategy:shibboleth.DataSealerKeyStrategy}'.trim()}"
+ p:lockedAtStartup="#{!environment.containsProperty('idp.sealer.keyStrategy') and (!environment.containsProperty('idp.sealer.storePassword') or !environment.containsProperty('idp.sealer.keyPassword')) }" />
+
+ <bean id="DefaultOAuth2DPoPNonceGenerator"
+ class="net.shibboleth.idp.plugin.oidc.op.security.jwt.claims.impl.DefaultDPoPProofNonceGenerator"
+ p:objectMapper-ref="shibboleth.oidc.JSONObjectMapper"
+ p:nonceLifetime="%{idp.oauth2.dpop.nonceLifetime:PT5M}"
+ c:sealer-ref="DefaultDPoPNonceSealer">
+
+ </bean>
</beans>
diff --git a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcApiFlowTest.java b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcApiFlowTest.java
index d83898d5..8781dc01 100644
--- a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcApiFlowTest.java
+++ b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcApiFlowTest.java
@@ -24,6 +24,7 @@ import java.util.Collection;
import java.util.Date;
import java.util.List;
+import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import com.nimbusds.jose.Algorithm;
@@ -201,5 +202,25 @@ public class AbstractOidcApiFlowTest extends AbstractOidcFlowTest {
}
throw new JOSEException("Unsupported algorithm " + jwsAlgorithm.getName());
}
-
+
+ protected String createValidDPoPNonce() {
+ final Instant exp = Instant.now().plusSeconds(300);
+ try {
+ return getDataSealer().wrap("{\"exp\":\"" + exp.toEpochMilli() + "\",\"jti\":\"mock\"}");
+ } catch (DataSealerException e) {
+ Assert.fail("Could not create nonce", e);
+ }
+ return null;
+ }
+
+ protected String createExpiredDPoPNonce() {
+ final Instant exp = Instant.now();
+ try {
+ return getDataSealer().wrap("{\"exp\":\"" + exp.toEpochMilli() + "\",\"jti\":\"mock\"}");
+ } catch (DataSealerException e) {
+ Assert.fail("Could not create nonce", e);
+ }
+ return null;
+ }
+
}
\ No newline at end of file
diff --git a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcFlowTest.java b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcFlowTest.java
index a290d890..ff431a5f 100644
--- a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcFlowTest.java
+++ b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/AbstractOidcFlowTest.java
@@ -86,6 +86,7 @@ import com.nimbusds.oauth2.sdk.dpop.DefaultDPoPProofFactory;
import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.oauth2.sdk.token.AccessToken;
import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
+import com.nimbusds.openid.connect.sdk.Nonce;
import com.nimbusds.openid.connect.sdk.claims.ClaimsSet;
import com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation;
import com.nimbusds.openid.connect.sdk.rp.OIDCClientMetadata;
@@ -605,21 +606,31 @@ public abstract class AbstractOidcFlowTest extends AbstractFlowTest {
}
protected static SignedJWT buildDPoPProof(final String method, final String uri) {
- return buildDPoPProof(method, uri, null);
+ return buildDPoPProof(method, uri, (AccessToken) null);
+ }
+
+ protected static SignedJWT buildDPoPProof(final String method, final String uri, final String nonce) {
+ return buildDPoPProof(method, uri, null, nonce);
}
protected static SignedJWT buildDPoPProof(final String method, final String uri, final AccessToken accessToken) {
- return buildDPoPProof(defaultDPoPProofKey(), JWSAlgorithm.ES256, method, uri, accessToken);
+ return buildDPoPProof(defaultDPoPProofKey(), JWSAlgorithm.ES256, method, uri, accessToken, null);
+ }
+
+ protected static SignedJWT buildDPoPProof(final String method, final String uri, final AccessToken accessToken,
+ final String nonce) {
+ return buildDPoPProof(defaultDPoPProofKey(), JWSAlgorithm.ES256, method, uri, accessToken, nonce);
}
protected static SignedJWT buildDPoPProof(final JWK jwk, final JWSAlgorithm alg, final String method,
- final String uri, final AccessToken accessToken) {
+ final String uri, final AccessToken accessToken, final String nonceValue) {
+ final Nonce nonce = nonceValue == null ? null : new Nonce(nonceValue);
try {
DPoPProofFactory proofFactory = new DefaultDPoPProofFactory(jwk, alg);
if (accessToken == null) {
- return proofFactory.createDPoPJWT(method, new URI(uri));
+ return proofFactory.createDPoPJWT(method, new URI(uri), null, nonce);
} else {
- return proofFactory.createDPoPJWT(method, new URI(uri), accessToken);
+ return proofFactory.createDPoPJWT(method, new URI(uri), accessToken, nonce);
}
} catch (JOSEException | URISyntaxException e) {
Assert.fail("Could not create DPoP proof", e);
diff --git a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/PushedAuthorizeFlowTest.java b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/PushedAuthorizeFlowTest.java
index b173f6b9..e4ae2607 100644
--- a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/PushedAuthorizeFlowTest.java
+++ b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/PushedAuthorizeFlowTest.java
@@ -209,7 +209,8 @@ public class PushedAuthorizeFlowTest extends AbstractOidcClientAuthenticationFlo
public void testWithInvalidDPoPProof_thunbprintNotMatching() throws IOException, SessionException {
storeMetadata(storageService, clientId, clientSecret, scope, "https://example.org/cb");
setBasicAuth(clientId, clientSecret);
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oauth2/pushed-authorization").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oauth2/pushed-authorization",
+ createValidDPoPNonce()).serialize());
Map<String, String> requestParameters = createRequestParameters(clientId);
requestParameters.put("dpop_jkt", "notMatching");
setHttpFormRequest("POST", requestParameters);
@@ -217,12 +218,25 @@ public class PushedAuthorizeFlowTest extends AbstractOidcClientAuthenticationFlo
assertErrorCode(result, OAuth2Error.INVALID_DPOP_PROOF_CODE);
}
+ @SuppressWarnings("null")
+ @Test
+ public void testWithInvalidDPoPProof_mandatoryNonceMissing() throws IOException, SessionException {
+ storeMetadata(storageService, clientId, clientSecret, scope, "https://example.org/cb");
+ setBasicAuth(clientId, clientSecret);
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oauth2/pushed-authorization")
+ .serialize());
+ setHttpFormRequest("POST", createRequestParameters(clientId));
+ final FlowExecutionResult result = flowExecutor.launchExecution(FLOW_ID, null, externalContext);
+ assertErrorCode(result, OAuth2Error.USE_DPOP_NONCE_CODE);
+ }
+
@SuppressWarnings("null")
@Test
public void testWithValidDPoPProof() throws IOException, SessionException {
storeMetadata(storageService, clientId, clientSecret, scope, "https://example.org/cb");
setBasicAuth(clientId, clientSecret);
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oauth2/pushed-authorization").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oauth2/pushed-authorization",
+ createValidDPoPNonce()).serialize());
setHttpFormRequest("POST", createRequestParameters(clientId));
final FlowExecutionResult result = flowExecutor.launchExecution(FLOW_ID, null, externalContext);
assertSuccessResponse(result, clientId);
diff --git a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/TokenFlowTest.java b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/TokenFlowTest.java
index 6eff3d33..f5a35370 100644
--- a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/TokenFlowTest.java
+++ b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/TokenFlowTest.java
@@ -703,7 +703,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
.setScope(scope)
.setDpopProofJwkThumbprint("mockJkt");
final String authorizationCode = builder.build().serialize(getDataSealer());
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce()).serialize());
initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
"authorization_code",
@@ -716,7 +717,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
@Test
public void testDPoPValidGrantThumbprintIncludedMatchingProof() throws Exception {
final AuthorizeCodeClaimsSet.Builder builder = new AuthorizeCodeClaimsSet.Builder();
- final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token");
+ final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce());
builder.setJWTID(new SecureRandomIdentifierGenerationStrategy())
.setClientID(new ClientID(clientId))
.setIssuer("https://op.example.org")
@@ -757,7 +759,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
.setRedirectURI(new URI(redirectUri))
.setScope(scope);
final String authorizationCode = builder.build().serialize(getDataSealer());
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce()).serialize());
initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
"authorization_code",
@@ -810,7 +813,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
.setScope(scope)
.setDpopProofJwkThumbprint("mockJkt");
final String authorizationCode = builder.build().serialize(getDataSealer());
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce()).serialize());
initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
"authorization_code",
@@ -824,7 +828,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
public void testDPoPEnforcedValidGrantThumbprintIncludedMatchingProof() throws Exception {
final String clientId = clientIdDPoPAccessToken;
final AuthorizeCodeClaimsSet.Builder builder = new AuthorizeCodeClaimsSet.Builder();
- final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token");
+ final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce());
builder.setJWTID(new SecureRandomIdentifierGenerationStrategy())
.setClientID(new ClientID(clientId))
.setIssuer("https://op.example.org")
@@ -866,7 +871,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
.setRedirectURI(new URI(redirectUri))
.setScope(scope);
final String authorizationCode = builder.build().serialize(getDataSealer());
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce()).serialize());
initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
"authorization_code",
@@ -919,7 +925,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
.setScope(scope)
.setDpopProofJwkThumbprint("mockJkt");
final String authorizationCode = builder.build().serialize(getDataSealer());
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce()).serialize());
initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
"authorization_code",
@@ -930,7 +937,7 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
}
@Test
- public void testDPoPJwtEnforcedValidGrantThumbprintIncludedMatchingProof() throws Exception {
+ public void testDPoPJwtEnforcedValidGrantThumbprintIncludedMatchingProof_noMandatoryNonce() throws Exception {
final String clientId = clientIdDPoPJwtAccessToken;
final AuthorizeCodeClaimsSet.Builder builder = new AuthorizeCodeClaimsSet.Builder();
final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token");
@@ -948,6 +955,34 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
final String authorizationCode = builder.build().serialize(getDataSealer());
request.addHeader("DPoP", dpopProof.serialize());
+ initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
+ "authorization_code",
+ authorizationCode, clientId));
+ storeConsent(storageService, "jdoe", clientId, "mail");
+ final FlowExecutionResult result = flowExecutor.launchExecution(FLOW_ID, null, externalContext);
+ assertErrorCode(result, OAuth2Error.USE_DPOP_NONCE_CODE);
+ }
+
+ @Test
+ public void testDPoPJwtEnforcedValidGrantThumbprintIncludedMatchingProof() throws Exception {
+ final String clientId = clientIdDPoPJwtAccessToken;
+ final AuthorizeCodeClaimsSet.Builder builder = new AuthorizeCodeClaimsSet.Builder();
+ final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce());
+ builder.setJWTID(new SecureRandomIdentifierGenerationStrategy())
+ .setClientID(new ClientID(clientId))
+ .setIssuer("https://op.example.org")
+ .setPrincipal("jdoe")
+ .setSubject("mock")
+ .setIssuedAt(Instant.now())
+ .setExpiresAt(Instant.now().plusSeconds(100))
+ .setAuthenticationTime(Instant.now())
+ .setRedirectURI(new URI(redirectUri))
+ .setScope(scope)
+ .setDpopProofJwkThumbprint(dpopProof.getHeader().getJWK().computeThumbprint().toString());
+ final String authorizationCode = builder.build().serialize(getDataSealer());
+ request.addHeader("DPoP", dpopProof.serialize());
+
initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
"authorization_code",
authorizationCode, clientId));
@@ -975,7 +1010,8 @@ public class TokenFlowTest extends AbstractOidcClientAuthenticationFlowTest {
.setRedirectURI(new URI(redirectUri))
.setScope(scope);
final String authorizationCode = builder.build().serialize(getDataSealer());
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/token",
+ createValidDPoPNonce()).serialize());
initializeGrantAndRequest(clientId, createRequestParameters(redirectUri,
"authorization_code",
diff --git a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/UserInfoTest.java b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/UserInfoTest.java
index 8a73e8b8..d1730cce 100644
--- a/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/UserInfoTest.java
+++ b/idp-oidc-extension-impl/src/test/java/net/shibboleth/idp/plugin/oidc/op/profile/flow/UserInfoTest.java
@@ -292,7 +292,8 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
JOSEException {
final AccessTokenClaimsSet claims = buildDPoPAccessTokenClaimsSet("mockId");
final DPoPAccessToken token = new DPoPAccessToken(claims.serialize(getDataSealer()));
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo",
+ createValidDPoPNonce()).serialize());
storeMetadata(storageService, clientId, "mockSecret", scope);
request.addHeader("Authorization", getTokenHeaderValue(token));
@@ -307,7 +308,8 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
JOSEException {
final AccessTokenClaimsSet claims = buildDPoPAccessTokenClaimsSet("mockId");
final DPoPAccessToken token = buildJWTDPoPToken(claims, signingKey.getPrivateKey(), "RS256");
- request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo").serialize());
+ request.addHeader("DPoP", buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo",
+ createValidDPoPNonce()).serialize());
storeMetadata(storageService, clientId, "mockSecret", scope);
request.addHeader("Authorization", getTokenHeaderValue(token));
@@ -319,7 +321,8 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
@Test
public void testFailWithDPoP_noAth() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
ComponentInitializationException, IOException, com.nimbusds.oauth2.sdk.ParseException, JOSEException {
- final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo");
+ final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo",
+ createValidDPoPNonce());
final AccessTokenClaimsSet claims =
buildDPoPAccessTokenClaimsSet((dpopProof.getHeader().getJWK().computeThumbprint().toString()));
@@ -336,7 +339,8 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
@Test
public void testFailWithDPoP_nonMatchingAth() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
ComponentInitializationException, IOException, com.nimbusds.oauth2.sdk.ParseException, JOSEException {
- final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo", new DPoPAccessToken("mock"));
+ final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo",
+ new DPoPAccessToken("mock"), createValidDPoPNonce());
final AccessTokenClaimsSet claims =
buildDPoPAccessTokenClaimsSet((dpopProof.getHeader().getJWK().computeThumbprint().toString()));
@@ -349,6 +353,25 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
assertErrorCode(result, OAuth2Error.INVALID_DPOP_PROOF_CODE);
}
+ @SuppressWarnings("null")
+ @Test
+ public void testFailWithDPoP_noMandatoryNonce() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
+ ComponentInitializationException, IOException, com.nimbusds.oauth2.sdk.ParseException, JOSEException {
+ final ECKey dpopProofKey = defaultDPoPProofKey();
+ final AccessTokenClaimsSet claims =
+ buildDPoPAccessTokenClaimsSet(dpopProofKey.computeThumbprint().toString());
+
+ final DPoPAccessToken token = new DPoPAccessToken(claims.serialize(getDataSealer()));
+ final SignedJWT dpopProof = buildDPoPProof(dpopProofKey, JWSAlgorithm.ES256, "POST",
+ "http://localhost/idp/profile/oidc/userinfo", token, null);
+ request.addHeader("DPoP", dpopProof.serialize());
+
+ storeMetadata(storageService, clientId, "mockSecret", scope);
+ request.addHeader("Authorization", getTokenHeaderValue(token));
+ final FlowExecutionResult result = flowExecutor.launchExecution(FLOW_ID, null, externalContext);
+ assertErrorCode(result, OAuth2Error.USE_DPOP_NONCE_CODE);
+ }
+
@SuppressWarnings("null")
@Test
public void testSuccessOnlySubjectWithDPoP() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
@@ -359,7 +382,7 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
final DPoPAccessToken token = new DPoPAccessToken(claims.serialize(getDataSealer()));
final SignedJWT dpopProof = buildDPoPProof(dpopProofKey, JWSAlgorithm.ES256, "POST",
- "http://localhost/idp/profile/oidc/userinfo", token);
+ "http://localhost/idp/profile/oidc/userinfo", token, createValidDPoPNonce());
request.addHeader("DPoP", dpopProof.serialize());
storeMetadata(storageService, clientId, "mockSecret", scope);
@@ -378,7 +401,8 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
@Test
public void testFailWithJWTDPoP_noAth() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
ComponentInitializationException, IOException, com.nimbusds.oauth2.sdk.ParseException, JOSEException {
- final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo");
+ final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo",
+ createValidDPoPNonce());
final AccessTokenClaimsSet claims =
buildDPoPAccessTokenClaimsSet((dpopProof.getHeader().getJWK().computeThumbprint().toString()));
@@ -395,7 +419,8 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
@Test
public void testFailWithJWTDPoP_nonMatchingAth() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
ComponentInitializationException, IOException, com.nimbusds.oauth2.sdk.ParseException, JOSEException {
- final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo", new DPoPAccessToken("mock"));
+ final SignedJWT dpopProof = buildDPoPProof("POST", "http://localhost/idp/profile/oidc/userinfo",
+ new DPoPAccessToken("mock"), createValidDPoPNonce());
final AccessTokenClaimsSet claims =
buildDPoPAccessTokenClaimsSet((dpopProof.getHeader().getJWK().computeThumbprint().toString()));
@@ -408,6 +433,25 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
assertErrorCode(result, OAuth2Error.INVALID_DPOP_PROOF_CODE);
}
+ @SuppressWarnings("null")
+ @Test
+ public void testFailWithJWTDPoP_noMandatoryNonce() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
+ ComponentInitializationException, IOException, com.nimbusds.oauth2.sdk.ParseException, JOSEException {
+ final ECKey dpopProofKey = defaultDPoPProofKey();
+ final AccessTokenClaimsSet claims =
+ buildDPoPAccessTokenClaimsSet(dpopProofKey.computeThumbprint().toString());
+
+ final DPoPAccessToken token = buildJWTDPoPToken(claims, signingKey.getPrivateKey(), "RS256");
+ final SignedJWT dpopProof = buildDPoPProof(dpopProofKey, JWSAlgorithm.ES256, "POST",
+ "http://localhost/idp/profile/oidc/userinfo", token, null);
+ request.addHeader("DPoP", dpopProof.serialize());
+
+ storeMetadata(storageService, clientId, "mockSecret", scope);
+ request.addHeader("Authorization", getTokenHeaderValue(token));
+ final FlowExecutionResult result = flowExecutor.launchExecution(FLOW_ID, null, externalContext);
+ assertErrorCode(result, OAuth2Error.USE_DPOP_NONCE_CODE);
+ }
+
@SuppressWarnings("null")
@Test
public void testSuccessOnlySubjectWithDPoPJWTNoAudience() throws URISyntaxException, NoSuchAlgorithmException, DataSealerException,
@@ -418,7 +462,7 @@ public class UserInfoTest extends AbstractOidcApiFlowTest {
final DPoPAccessToken token = buildJWTDPoPToken(claims, signingKey.getPrivateKey(), "RS256");
final SignedJWT dpopProof = buildDPoPProof(dpopProofKey, JWSAlgorithm.ES256, "POST",
- "http://localhost/idp/profile/oidc/userinfo", token);
+ "http://localhost/idp/profile/oidc/userinfo", token, createValidDPoPNonce());
request.addHeader("DPoP", dpopProof.serialize());
storeMetadata(storageService, clientId, "mockSecret", scope);
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.
More information about the commits
mailing list