org.jose4j.jwk.HttpsJwks Java Examples

The following examples show how to use org.jose4j.jwk.HttpsJwks. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadHttpsJwksMathchingKid() throws Exception {
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo("https://github.com/my_key.jwks", "issuer");
    contextInfo.setJwksRefreshInterval(10);

    KeyLocationResolver keyLocationResolver = new KeyLocationResolver(contextInfo) {
        protected HttpsJwks initializeHttpsJwks() {
            return httpsJwks;
        }
    };
    RsaJsonWebKey jwk = new RsaJsonWebKey(key);
    jwk.setKeyId("1");
    when(httpsJwks.getJsonWebKeys()).thenReturn(Collections.singletonList(jwk));
    keyLocationResolver = Mockito.spy(keyLocationResolver);
    when(signature.getHeaders()).thenReturn(headers);
    when(headers.getStringHeaderValue(JsonWebKey.KEY_ID_PARAMETER)).thenReturn("1");

    assertEquals(key, keyLocationResolver.resolveKey(signature, emptyList()));
    assertNull(keyLocationResolver.verificationKey);
}
 
Example #2
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadHttpsPemCrt() throws Exception {
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo("https://github.com/my_key.crt", "issuer");
    contextInfo.setJwksRefreshInterval(10);

    Mockito.doThrow(new JoseException("")).when(httpsJwks).refresh();
    Mockito.doReturn(ResourceUtils.getAsClasspathResource("publicCrt.pem"))
            .when(urlResolver).resolve(Mockito.any());
    KeyLocationResolver keyLocationResolver = new KeyLocationResolver(contextInfo) {
        protected HttpsJwks initializeHttpsJwks() {
            return httpsJwks;
        }

        protected UrlStreamResolver getUrlResolver() {
            return urlResolver;
        }
    };
    assertNotNull(keyLocationResolver.verificationKey);
    assertEquals(keyLocationResolver.verificationKey, keyLocationResolver.resolveKey(signature, emptyList()));
    assertEquals(keyLocationResolver.verificationKey,
            KeyLocationResolver.tryAsPEMCertificate(keyLocationResolver.readKeyContent("publicCrt.pem")));
}
 
Example #3
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadHttpsJwksNonMathchingKidAndRefresh() throws Exception {
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo("https://github.com/my_key.jwks", "issuer");
    contextInfo.setJwksRefreshInterval(10);

    KeyLocationResolver keyLocationResolver = new KeyLocationResolver(contextInfo) {
        protected HttpsJwks initializeHttpsJwks() {
            return httpsJwks;
        }
    };
    // token 'kid' is '1'
    when(signature.getHeaders()).thenReturn(headers);
    when(headers.getStringHeaderValue(JsonWebKey.KEY_ID_PARAMETER)).thenReturn("1");

    final RsaJsonWebKey jwk = new RsaJsonWebKey(key);

    // Return JWK Set with a non-matching JWK with 'kid' set to '2' 
    jwk.setKeyId("2");
    when(httpsJwks.getJsonWebKeys()).thenReturn(Collections.singletonList(jwk));

    // Refresh JWK Set and get a matching JWK with 'kid' set to '1'
    doAnswer((i) -> {
        jwk.setKeyId("1");
        return null;
    }).when(httpsJwks).refresh();

    keyLocationResolver = Mockito.spy(keyLocationResolver);
    assertEquals(key, keyLocationResolver.resolveKey(signature, emptyList()));
    assertNull(keyLocationResolver.verificationKey);
}
 
Example #4
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnresolvableKeyException.class)
public void testLoadHttpsJwksNonMathchingKidAndRefreshDeclined() throws Exception {
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo("https://github.com/my_key.jwks", "issuer");
    contextInfo.setJwksRefreshInterval(10);
    contextInfo.setForcedJwksRefreshInterval(10);

    KeyLocationResolver keyLocationResolver = new KeyLocationResolver(contextInfo) {
        protected HttpsJwks initializeHttpsJwks() {
            return httpsJwks;
        }
    };
    // token 'kid' is '1'
    when(signature.getHeaders()).thenReturn(headers);
    when(headers.getStringHeaderValue(JsonWebKey.KEY_ID_PARAMETER)).thenReturn("1");

    final RsaJsonWebKey jwk = new RsaJsonWebKey(key);

    // Return JWK Set with a non-matching JWK with 'kid' set to '2' 
    jwk.setKeyId("2");
    when(httpsJwks.getJsonWebKeys()).thenReturn(Collections.singletonList(jwk));

    // Refresh JWK Set and get a matching JWK with 'kid' set to '1'
    doAnswer((i) -> {
        jwk.setKeyId("1");
        return null;
    }).when(httpsJwks).refresh();

    keyLocationResolver = Mockito.spy(keyLocationResolver);
    assertEquals(key, keyLocationResolver.resolveKey(signature, emptyList()));
    assertNull(keyLocationResolver.verificationKey);

    // Return JWK Set with a non-matching JWK with 'kid' set to '2'
    jwk.setKeyId("2");
    keyLocationResolver.resolveKey(signature, emptyList());
}
 
Example #5
Source File: Jose4jJWKSTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void validateToken(String token, URL jwksURL, String issuer, int expGracePeriodSecs) throws Exception {
    JwtConsumerBuilder builder = new JwtConsumerBuilder()
        .setRequireExpirationTime()
        .setRequireSubject()
        .setSkipDefaultAudienceValidation()
        .setExpectedIssuer(issuer)
        .setJwsAlgorithmConstraints(
            new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
                                     AlgorithmIdentifiers.RSA_USING_SHA256));

    HttpsJwks keySource = new HttpsJwks(jwksURL.toExternalForm());
    List<JsonWebKey> keys = keySource.getJsonWebKeys();
    JsonWebKey key = keys.get(0);
    if(key instanceof PublicJsonWebKey) {
        PublicJsonWebKey publicJsonWebKey = (PublicJsonWebKey) key;
        PublicKey pk = publicJsonWebKey.getPublicKey();
        byte[] encoded = pk.getEncoded();
        String pem = Base64.getEncoder().encodeToString(encoded);
        System.out.printf("pk.pem: %s\n", pem);
    }
    builder.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(keySource));

    if (expGracePeriodSecs > 0) {
        builder.setAllowedClockSkewInSeconds(expGracePeriodSecs);
    }
    else {
        builder.setEvaluationTime(NumericDate.fromSeconds(0));
    }

    JwtConsumer jwtConsumer = builder.build();
    JwtContext jwtContext = jwtConsumer.process(token);
    String type = jwtContext.getJoseObjects().get(0).getHeader("typ");
    //  Validate the JWT and process it to the Claims
    jwtConsumer.processContext(jwtContext);

}
 
Example #6
Source File: JWTIssuerConfig.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private HttpsJwks create(String url) {
  try {
    URL jwksUrl = new URL(url);
    if (!"https".equalsIgnoreCase(jwksUrl.getProtocol())) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, PARAM_JWKS_URL + " must use HTTPS");
    }
  } catch (MalformedURLException e) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Url " + url + " configured in " + PARAM_JWKS_URL + " is not a valid URL");
  }
  HttpsJwks httpsJkws = new HttpsJwks(url);
  httpsJkws.setDefaultCacheDuration(jwkCacheDuration);
  httpsJkws.setRefreshReprieveThreshold(refreshReprieveThreshold);
  return httpsJkws;
}
 
Example #7
Source File: KeyLocationResolver.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
protected HttpsJwks initializeHttpsJwks() {
    return new HttpsJwks(authContextInfo.getPublicKeyLocation());
}
 
Example #8
Source File: JWTAuthPlugin.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Main authentication method that looks for correct JWT token in the Authorization header
 */
@Override
public boolean doAuthenticate(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws Exception {
  String header = request.getHeader(HttpHeaders.AUTHORIZATION);

  if (jwtConsumer == null) {
    if (header == null && !blockUnknown) {
      log.info("JWTAuth not configured, but allowing anonymous access since {}==false", PARAM_BLOCK_UNKNOWN);
      numPassThrough.inc();
      filterChain.doFilter(request, response);
      return true;
    }
    // Retry config
    if (lastInitTime.plusSeconds(RETRY_INIT_DELAY_SECONDS).isAfter(Instant.now())) {
      log.info("Retrying JWTAuthPlugin initialization (retry delay={}s)", RETRY_INIT_DELAY_SECONDS);
      init(pluginConfig);
    }
    if (jwtConsumer == null) {
      log.warn("JWTAuth not configured");
      numErrors.mark();
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "JWTAuth plugin not correctly configured");
    }
  }

  JWTAuthenticationResponse authResponse = authenticate(header);
  String exceptionMessage = authResponse.getJwtException() != null ? authResponse.getJwtException().getMessage() : "";
  if (AuthCode.SIGNATURE_INVALID.equals(authResponse.getAuthCode())) {
    String issuer = jwtConsumer.processToClaims(header).getIssuer();
    if (issuer != null) {
      Optional<JWTIssuerConfig> issuerConfig = issuerConfigs.stream().filter(ic -> issuer.equals(ic.getIss())).findFirst();
      if (issuerConfig.isPresent() && issuerConfig.get().usesHttpsJwk()) {
        log.info("Signature validation failed for issuer {}. Refreshing JWKs from IdP before trying again: {}",
            issuer, exceptionMessage);
        for (HttpsJwks httpsJwks : issuerConfig.get().getHttpsJwks()) {
          httpsJwks.refresh();
        }
        authResponse = authenticate(header); // Retry
        exceptionMessage = authResponse.getJwtException() != null ? authResponse.getJwtException().getMessage() : "";
      }
    }
  }

  switch (authResponse.getAuthCode()) {
    case AUTHENTICATED:
      final Principal principal = authResponse.getPrincipal();
      request = wrapWithPrincipal(request, principal);
      if (!(principal instanceof JWTPrincipal)) {
        numErrors.mark();
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "JWTAuth plugin says AUTHENTICATED but no token extracted");
      }
      if (log.isDebugEnabled())
        log.debug("Authentication SUCCESS");
      numAuthenticated.inc();
      filterChain.doFilter(request, response);
      return true;

    case PASS_THROUGH:
      if (log.isDebugEnabled())
        log.debug("Unknown user, but allow due to {}=false", PARAM_BLOCK_UNKNOWN);
      numPassThrough.inc();
      request.setAttribute(AuthenticationPlugin.class.getName(), getPromptHeaders(null, null));
      filterChain.doFilter(request, response);
      return true;

    case AUTZ_HEADER_PROBLEM:
    case JWT_PARSE_ERROR:
      log.warn("Authentication failed. {}, {}", authResponse.getAuthCode(), authResponse.getAuthCode().getMsg());
      numErrors.mark();
      authenticationFailure(response, authResponse.getAuthCode().getMsg(), HttpServletResponse.SC_BAD_REQUEST, BearerWwwAuthErrorCode.invalid_request);
      return false;

    case CLAIM_MISMATCH:
    case JWT_EXPIRED:
    case JWT_VALIDATION_EXCEPTION:
    case PRINCIPAL_MISSING:
      log.warn("Authentication failed. {}, {}", authResponse.getAuthCode(), exceptionMessage);
      numWrongCredentials.inc();
      authenticationFailure(response, authResponse.getAuthCode().getMsg(), HttpServletResponse.SC_UNAUTHORIZED, BearerWwwAuthErrorCode.invalid_token);
      return false;

    case SIGNATURE_INVALID:
      log.warn("Signature validation failed: {}", exceptionMessage);
      numWrongCredentials.inc();
      authenticationFailure(response, authResponse.getAuthCode().getMsg(), HttpServletResponse.SC_UNAUTHORIZED, BearerWwwAuthErrorCode.invalid_token);
      return false;

    case SCOPE_MISSING:
      numWrongCredentials.inc();
      authenticationFailure(response, authResponse.getAuthCode().getMsg(), HttpServletResponse.SC_UNAUTHORIZED, BearerWwwAuthErrorCode.insufficient_scope);
      return false;

    case NO_AUTZ_HEADER:
    default:
      numMissingCredentials.inc();
      authenticationFailure(response, authResponse.getAuthCode().getMsg(), HttpServletResponse.SC_UNAUTHORIZED, null);
      return false;
  }
}
 
Example #9
Source File: JWTIssuerConfig.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public List<HttpsJwks> getHttpsJwks() {
  if (httpsJwks == null) {
    httpsJwks = httpsJwksFactory.createList(getJwksUrls());
  }
  return httpsJwks;
}
 
Example #10
Source File: JWTIssuerConfig.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public List<HttpsJwks> createList(List<String> jwkUrls) {
  return jwkUrls.stream().map(this::create).collect(Collectors.toList());
}
 
Example #11
Source File: HttpsJwksVerificationKeyResolver.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public HttpsJwksVerificationKeyResolver(HttpsJwks httpsJkws)
{
    this.httpsJkws = httpsJkws;
}