Search in sources :

Example 16 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project wildfly-swarm by wildfly-swarm.

the class JWTCredential method getName.

/**
 * This just parses the token without validation to extract one of the following in order to obtain
 * the name to be used for the principal:
 * upn
 * preferred_username
 * subject
 *
 * If there is an exception it sets the name to INVALID_TOKEN_NAME and saves the exception for access
 * via {@link #getJwtException()}
 *
 * @return the name to use for the principal
 */
public String getName() {
    if (name == null) {
        name = "INVALID_TOKEN_NAME";
        try {
            // Build a JwtConsumer that doesn't check signatures or do any validation.
            JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
            // The first JwtConsumer is basically just used to parse the JWT into a JwtContext object.
            JwtContext jwtContext = firstPassJwtConsumer.process(bearerToken);
            JwtClaims claimsSet = jwtContext.getJwtClaims();
            // We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
            name = claimsSet.getClaimValue("upn", String.class);
            if (name == null) {
                name = claimsSet.getClaimValue("preferred_username", String.class);
                if (name == null) {
                    name = claimsSet.getSubject();
                }
            }
        } catch (Exception e) {
            jwtException = e;
        }
    }
    return name;
}
Also used : JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext)

Example 17 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project digilib by robcast.

the class OpenIdAuthnOps method init.

/* (non-Javadoc)
     * @see digilib.auth.AuthnOps#init(digilib.conf.DigilibConfiguration)
     */
@Override
public void init(DigilibConfiguration dlConfig) throws AuthOpException {
    configFile = dlConfig.getAsFile("auth-file");
    logger.debug("openidauthnops.init (" + configFile + ")");
    List<Map<String, String>> idpList;
    try {
        // load identity providers
        XMLMapListLoader idpLoader = new XMLMapListLoader("digilib-oauth", "openid");
        idpList = idpLoader.loadUri(configFile.toURI());
    } catch (Exception e) {
        throw new AuthOpException("ERROR loading auth config file: " + e);
    }
    if (idpList == null) {
        throw new AuthOpException("ERROR unable to load auth config file!");
    }
    // create Map of roles by issuer
    idpRoles = new HashMap<String, List<String>>();
    // build a first pass JwtConsumer that doesn't check signatures or do any validation.
    firstPassJwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
    // create Map of configured JwtConsumers by issuer
    idpJwtConsumers = new HashMap<String, JwtConsumer>();
    for (Map<String, String> idpDesc : idpList) {
        String issuer = idpDesc.get("issuer");
        if (issuer == null) {
            logger.error("Missing issuer in openid tag!");
            continue;
        }
        String clientid = idpDesc.get("clientid");
        if (clientid == null) {
            logger.error("Missing clientid in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        String rolestr = idpDesc.get("roles");
        if (rolestr == null) {
            logger.error("Missing roles in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        // split roles string into list
        List<String> roles = Arrays.asList(rolestr.split(","));
        String keytype = idpDesc.get("keytype");
        if (keytype == null || !keytype.equals("jwk")) {
            logger.error("Missing or invalid keytype in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        String keyData = idpDesc.get("_text");
        if (keyData == null || keyData.length() == 0) {
            logger.error("Missing key data in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        try {
            // create key from JWK data
            JsonWebKey jwk = JsonWebKey.Factory.newJwk(keyData);
            // create second pass consumer for validation
            JwtConsumer secondPassJwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(issuer).setVerificationKey(jwk.getKey()).setRequireExpirationTime().setAllowedClockSkewInSeconds(300).setRequireSubject().setExpectedAudience(clientid).build();
            // save consumer and roles
            idpJwtConsumers.put(issuer, secondPassJwtConsumer);
            idpRoles.put(issuer, roles);
            logger.debug("Registered id provider '" + issuer + "'");
        } catch (JoseException e) {
            logger.error("Invalid key data in openid tag! (issuer: " + issuer + ")");
            continue;
        }
    }
    // set token cookie name
    tokenCookieName = dlConfig.getAsString("authn-token-cookie");
}
Also used : XMLMapListLoader(digilib.util.XMLMapListLoader) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JoseException(org.jose4j.lang.JoseException) JsonWebKey(org.jose4j.jwk.JsonWebKey) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JoseException(org.jose4j.lang.JoseException) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 18 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project tomee by apache.

the class PublicKeyAsJWKSTest method validateJWKS.

@Test
public void validateJWKS() throws Exception {
    System.setProperty(Names.VERIFIER_PUBLIC_KEY, "");
    System.setProperty(Names.VERIFIER_PUBLIC_KEY_LOCATION, "file://" + Paths.get("").toAbsolutePath().toString() + "/src/test/resources/signer-keyset4k.jwk");
    System.setProperty(Names.ISSUER, TCKConstants.TEST_ISSUER);
    final PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey4k.pem");
    final String kid = "publicKey4k";
    final String token = TokenUtils.generateTokenString(privateKey, kid, "/Token1.json", null, new HashMap<>());
    System.out.println("token = " + token);
    final JWTAuthConfigurationProperties JWTAuthConfigurationProperties = new JWTAuthConfigurationProperties();
    JWTAuthConfigurationProperties.init(null);
    final JWTAuthConfiguration jwtAuthConfiguration = JWTAuthConfigurationProperties.getJWTAuthConfiguration().orElseThrow(IllegalArgumentException::new);
    final JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder().setRequireExpirationTime().setRequireSubject().setSkipDefaultAudienceValidation().setExpectedIssuer(jwtAuthConfiguration.getIssuer()).setJwsAlgorithmConstraints(new AlgorithmConstraints(WHITELIST, RSA_USING_SHA256)).setSkipDefaultAudienceValidation().setVerificationKey(jwtAuthConfiguration.getPublicKey());
    if (jwtAuthConfiguration.getExpGracePeriodSecs() > 0) {
        jwtConsumerBuilder.setAllowedClockSkewInSeconds(jwtAuthConfiguration.getExpGracePeriodSecs());
    } else {
        jwtConsumerBuilder.setEvaluationTime(NumericDate.fromSeconds(0));
    }
    if (jwtAuthConfiguration.isSingleKey()) {
        jwtConsumerBuilder.setVerificationKey(jwtAuthConfiguration.getPublicKey());
    } else {
        jwtConsumerBuilder.setVerificationKeyResolver(new JwksVerificationKeyResolver(jwtAuthConfiguration.getPublicKeys()));
    }
    final JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    final JwtContext jwtContext = jwtConsumer.process(token);
    Assert.assertEquals(jwtContext.getJwtClaims().getStringClaimValue("upn"), "jdoe@example.com");
}
Also used : PrivateKey(java.security.PrivateKey) JWTAuthConfiguration(org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) JWTAuthConfigurationProperties(org.apache.tomee.microprofile.jwt.config.JWTAuthConfigurationProperties) AlgorithmConstraints(org.jose4j.jwa.AlgorithmConstraints) Test(org.testng.annotations.Test)

Example 19 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationServiceImplTest method anonymousUserToken.

@Test
public void anonymousUserToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    JenkinsRule.WebClient webClient = j.createWebClient();
    String token = getToken(webClient);
    Assert.assertNotNull(token);
    JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
    Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
    JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
    String kid = jsw.getHeader("kid");
    Assert.assertNotNull(kid);
    Page page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
    // for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
    // System.out.println(valuePair);
    // }
    JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
    RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKey(// verify the sign with the public key
    rsaJsonWebKey.getKey()).build();
    JwtClaims claims = jwtConsumer.processToClaims(token);
    Assert.assertEquals("anonymous", claims.getSubject());
    Map<String, Object> claimMap = claims.getClaimsMap();
    Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
    Map<String, String> userContext = (Map<String, String>) context.get("user");
    Assert.assertEquals("anonymous", userContext.get("id"));
}
Also used : JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Page(com.gargoylesoftware.htmlunit.Page) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JSONObject(net.sf.json.JSONObject) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Map(java.util.Map) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) Test(org.junit.Test)

Aggregations

JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)19 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)18 JwtClaims (org.jose4j.jwt.JwtClaims)15 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)11 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)10 JwtContext (org.jose4j.jwt.consumer.JwtContext)9 Map (java.util.Map)6 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)6 JSONObject (net.sf.json.JSONObject)5 Test (org.junit.Test)5 JenkinsRule (org.jvnet.hudson.test.JenkinsRule)5 Page (com.gargoylesoftware.htmlunit.Page)4 RsaJsonWebKey (org.jose4j.jwk.RsaJsonWebKey)4 JsonWebSignature (org.jose4j.jws.JsonWebSignature)4 JoseException (org.jose4j.lang.JoseException)4 User (hudson.model.User)3 Mailer (hudson.tasks.Mailer)3 AlgorithmConstraints (org.jose4j.jwa.AlgorithmConstraints)3 JwksVerificationKeyResolver (org.jose4j.keys.resolvers.JwksVerificationKeyResolver)3 ServiceException (io.jenkins.blueocean.commons.ServiceException)2