[java-oidc-common] branch main updated: JCOMOIDC-53 - Add access token at_hash validator

Phil Smart philip.smart at jisc.ac.uk
Thu Dec 1 10:34:52 UTC 2022


This is an automated email from the git hooks/post-receive script.

philsmart pushed a commit to branch main
in repository java-oidc-common.

View the commit online:
http://git.shibboleth.net/view/?p=java-oidc-common.git;a=commit;h=ab8749e7a8405b4f19a68141c8f63251660b6610

The following commit(s) were added to refs/heads/main by this push:
     new ab8749e  JCOMOIDC-53 - Add access token at_hash validator
ab8749e is described below

commit ab8749e7a8405b4f19a68141c8f63251660b6610
Author: Phil Smart <philip.smart at jisc.ac.uk>
AuthorDate: Thu Dec 1 10:34:50 2022 +0000

    JCOMOIDC-53 - Add access token at_hash validator
    
    https://shibboleth.atlassian.net/browse/JCOMOIDC-53
---
 .../jwt/claims/impl/AccessTokenHashValidator.java  | 152 +++++++++++++++++++
 .../claims/impl/AccessTokenHashValidatorTest.java  | 161 +++++++++++++++++++++
 2 files changed, 313 insertions(+)

diff --git a/oidc-common-crypto-impl/src/main/java/net/shibboleth/oidc/security/jwt/claims/impl/AccessTokenHashValidator.java b/oidc-common-crypto-impl/src/main/java/net/shibboleth/oidc/security/jwt/claims/impl/AccessTokenHashValidator.java
new file mode 100644
index 0000000..d286ad3
--- /dev/null
+++ b/oidc-common-crypto-impl/src/main/java/net/shibboleth/oidc/security/jwt/claims/impl/AccessTokenHashValidator.java
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the University Corporation for Advanced Internet Development,
+ * Inc. (UCAID) under one or more contributor license agreements.  See the
+ * NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The UCAID licenses this file to You 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.oidc.security.jwt.claims.impl;
+
+import java.util.Map;
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.nimbusds.jose.JWSHeader;
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.oauth2.sdk.ParseException;
+import com.nimbusds.oauth2.sdk.token.AccessToken;
+import com.nimbusds.openid.connect.sdk.claims.AccessTokenHash;
+import com.nimbusds.openid.connect.sdk.validators.AccessTokenValidator;
+import com.nimbusds.openid.connect.sdk.validators.InvalidHashException;
+
+import net.minidev.json.JSONObject;
+import net.shibboleth.oidc.jwt.claims.AbstractClaimsValidator;
+import net.shibboleth.oidc.jwt.claims.JWTValidationException;
+import net.shibboleth.utilities.java.support.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
+import net.shibboleth.utilities.java.support.component.ComponentSupport;
+import net.shibboleth.utilities.java.support.logic.Constraint;
+import net.shibboleth.utilities.java.support.primitive.StringSupport;
+
+/**
+ * A validator that checks the access_token value matches its encoded at_hash representation in the
+ * id_token. 
+ * 
+ * <p>Is essentially a facade to the Nimbus {@link AccessTokenValidator}.</p>
+ */
+public class AccessTokenHashValidator extends AbstractClaimsValidator {
+    
+    /** Class logger. */
+    @Nonnull private final Logger log = LoggerFactory.getLogger(AccessTokenHashValidator.class);
+    
+    /** Strategy to find the token response JSON object.*/
+    @NonnullAfterInit private Function<ProfileRequestContext, Map<String, Object>> tokenResponseLookupStrategy;
+    
+    /** Strategy to find the JOSE headers relating to the id_token the at_hash is taken from.*/
+    @NonnullAfterInit private Function<ProfileRequestContext, JWSHeader> joseHeaderLookupStrategy;
+    
+    /** Allow a missing at_hash claim. */
+    private boolean allowMissing;
+    
+    /**
+     * Set whether a missing 'at_hash' claim is valid or not.
+     * 
+     * <p>Defaults to false.</p>
+     * 
+     * @param flag flag to set
+     */
+    public void setAllowMissing(final boolean flag) {
+        allowMissing = flag;
+    }
+    
+    
+    /** 
+     * Set the lookup strategy used to locate the token response JSON object that contains the 
+     * access_token. 
+     * 
+     * @param strategy the strategy.
+     */
+    public void setTokenResponseLookupStrategy(final Function<ProfileRequestContext, Map<String, Object>> strategy) {
+        ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+        ComponentSupport.ifDestroyedThrowDestroyedComponentException(this);
+
+        tokenResponseLookupStrategy = Constraint.isNotNull(strategy,
+                "Token Response Lookup Strategy can not be null");
+    }
+    
+    /**
+     * Set the lookup strategy used to locate the JWS header of the id_token.
+     * 
+     * @param strategy the strategy.
+     */
+    public void setJoseHeaderLookupStrategy(final Function<ProfileRequestContext, JWSHeader> strategy) {
+        ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+        ComponentSupport.ifDestroyedThrowDestroyedComponentException(this);
+
+        joseHeaderLookupStrategy = Constraint.isNotNull(strategy, 
+                "Jose Header Lookup Strategy can not be null");
+    }
+
+    @Override
+    protected void doInitialize() throws ComponentInitializationException {
+        super.doInitialize();
+        
+        if (tokenResponseLookupStrategy == null) {
+            throw new ComponentInitializationException("Token lookup strategy can not be null");
+        }
+        if (joseHeaderLookupStrategy == null) {
+            throw new ComponentInitializationException("JOSE Header lookup strategy can not be null");
+        }
+    }
+
+    @Override
+    protected void doValidate(@Nonnull final JWTClaimsSet claims, @Nonnull final ProfileRequestContext context) 
+               throws JWTValidationException {
+
+        try {
+            final String atHashClaim = claims.getStringClaim("at_hash");
+            
+            if (StringSupport.trimOrNull(atHashClaim) == null) {
+                if (allowMissing) {
+                    log.debug("No at_hash claim present in id_token, no checks performed");
+                    return;
+                } else {
+                    throw new JWTValidationException("Required at_hash claim not present in id_token");
+                }
+            }
+            
+            final Map<String, Object> tokenResponse = tokenResponseLookupStrategy.apply(context);
+            if (tokenResponse == null) {
+                throw new JWTValidationException("Token response was not found, cannot validate 'at_hash' claim");
+            }
+            
+            final JWSHeader joseHeader = joseHeaderLookupStrategy.apply(context);  
+            if (joseHeader == null) {
+                throw new JWTValidationException("JWS Header from id_token not found, cannot validate 'at_hash' claim");
+            }
+            
+            final AccessToken accessToken = AccessToken.parse(new JSONObject(tokenResponse));            
+            AccessTokenValidator.validate(accessToken, joseHeader.getAlgorithm(), new AccessTokenHash(atHashClaim));
+            
+        } catch (final InvalidHashException | ParseException | java.text.ParseException e) {
+            throw new JWTValidationException(e);
+        }       
+        
+    }
+
+}
diff --git a/oidc-common-crypto-impl/src/test/java/net/shibboleth/oidc/security/jwt/claims/impl/AccessTokenHashValidatorTest.java b/oidc-common-crypto-impl/src/test/java/net/shibboleth/oidc/security/jwt/claims/impl/AccessTokenHashValidatorTest.java
new file mode 100644
index 0000000..149acb6
--- /dev/null
+++ b/oidc-common-crypto-impl/src/test/java/net/shibboleth/oidc/security/jwt/claims/impl/AccessTokenHashValidatorTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the University Corporation for Advanced Internet Development,
+ * Inc. (UCAID) under one or more contributor license agreements.  See the
+ * NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The UCAID licenses this file to You 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.oidc.security.jwt.claims.impl;
+
+import static org.testng.Assert.fail;
+
+import java.text.ParseException;
+import java.util.Map;
+
+import javax.annotation.Nonnull;
+
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.jose.JWSHeader;
+import com.nimbusds.jwt.JWTClaimsSet;
+
+import net.shibboleth.oidc.jwt.claims.JWTValidationException;
+import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
+
+/** Tests for the {@link AccessTokenHashValidator}.*/
+public class AccessTokenHashValidatorTest extends AbstractClaimsValidatorTest {
+    
+    /** The validator to test.*/
+    @Nonnull private AccessTokenHashValidator validator;
+    
+    @Override
+    @BeforeMethod
+    public void setup() throws ComponentInitializationException {
+        super.setup();
+        validator = new AccessTokenHashValidator();
+        validator.setAllowMissing(false);
+        validator.setId("test-validator");
+    }
+    
+    @Test(expectedExceptions = JWTValidationException.class)
+    public void doValidateTest_Mismatch() throws JWTValidationException, ComponentInitializationException {
+        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("at_hash", "bad-at-hash").build();
+        
+        validator.setJoseHeaderLookupStrategy(prc ->  {
+            try {
+                return JWSHeader.parse(Map.of("alg","RS256"));
+            } catch (final ParseException e) {
+                fail(e.getMessage());
+                return null;
+            }
+        });
+        validator.setTokenResponseLookupStrategy(prc -> Map.of("access_token", "token", "token_type","Bearer"));
+        
+        validator.initialize();
+        validator.validate(claimsSet, prc);
+    }
+    
+    @Test
+    public void doValidateTest_Success() throws JWTValidationException, ComponentInitializationException {
+        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("at_hash", "77QmUPtjPfzWtF2AnpK9RQ").build();
+        
+        validator.setJoseHeaderLookupStrategy(prc ->  {
+            try {
+                return JWSHeader.parse(Map.of("alg","RS256"));
+            } catch (final ParseException e) {
+                fail(e.getMessage());
+                return null;
+            }
+        });
+        validator.setTokenResponseLookupStrategy(prc -> 
+            Map.of("access_token", "jHkWEdUXMU1BwAsC4vtUsZwnNvTIxEl0z9K3vx5KF0Y", "token_type","Bearer"));
+        
+        validator.initialize();
+        validator.validate(claimsSet, prc);
+    }
+    
+    @Test(expectedExceptions = JWTValidationException.class)
+    public void doValidateTest_NoToken() throws JWTValidationException, ComponentInitializationException {
+        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("at_hash", "bad-at-hash").build();
+        
+        validator.setJoseHeaderLookupStrategy(prc ->  {
+            try {
+                return JWSHeader.parse(Map.of("alg","RS256"));
+            } catch (final ParseException e) {
+                fail(e.getMessage());
+                return null;
+            }
+        });
+        validator.setTokenResponseLookupStrategy(prc -> null);
+
+        validator.initialize();
+        validator.validate(claimsSet, prc);
+    }
+    
+    @Test(expectedExceptions = JWTValidationException.class)
+    public void doValidateTest_NoHeader() throws JWTValidationException, ComponentInitializationException {
+        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("at_hash", "bad-at-hash").build();
+        
+        validator.setJoseHeaderLookupStrategy(prc ->  null);
+        validator.setTokenResponseLookupStrategy(prc -> Map.of("access_token", "token", "token_type","Bearer"));
+
+        validator.initialize();
+        validator.validate(claimsSet, prc);
+    }
+    
+    @Test(expectedExceptions = JWTValidationException.class)
+    public void doValidateTest_NoAtHash_Required() throws JWTValidationException, ComponentInitializationException {
+        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().build();
+        validator.setAllowMissing(false);
+        validator.setJoseHeaderLookupStrategy(prc ->  {
+            try {
+                return JWSHeader.parse(Map.of("alg","RS256"));
+            } catch (final ParseException e) {
+                fail(e.getMessage());
+                return null;
+            }
+        });
+        validator.setTokenResponseLookupStrategy(prc -> Map.of("access_token", "token", "token_type","Bearer"));
+
+        validator.initialize();
+        validator.validate(claimsSet, prc);
+    }
+    
+    @Test
+    public void doValidateTest_NoAtHash_NotRequired() throws JWTValidationException, ComponentInitializationException {
+        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().build();
+        validator.setAllowMissing(true);
+        validator.setJoseHeaderLookupStrategy(prc ->  {
+            try {
+                return JWSHeader.parse(Map.of("alg","RS256"));
+            } catch (final ParseException e) {
+                fail(e.getMessage());
+                return null;
+            }
+        });
+        validator.setTokenResponseLookupStrategy(prc -> Map.of("access_token", "token", "token_type","Bearer"));
+
+        validator.initialize();
+        validator.validate(claimsSet, prc);
+    }
+    
+    @Test(expectedExceptions = ComponentInitializationException.class)
+    public void doValidateTest_NoStrategies() throws JWTValidationException, ComponentInitializationException {
+        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("at_hash", "bad-at-hash").build();
+        
+        validator.initialize();
+        validator.validate(claimsSet, prc);
+    }
+
+}

-- 
To stop receiving notification emails like this one, please contact
the administrator of this repository.


More information about the commits mailing list