org.jose4j.jwx.JsonWebStructure Java Examples

The following examples show how to use org.jose4j.jwx.JsonWebStructure. 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: DecryptAetIdentifiers.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Decrypt a payload encoded in a compact serialization of JSON Web Encryption (JWE).
 *
 * <p>The payload may be either a single JWE string or an array of values.
 *
 * <p>Assumes that the payload contains a "kid" parameter that can be used to look up a matching
 * private key.
 */
public static JsonNode decrypt(KeyStore keyStore, JsonNode anonIdNode)
    throws JoseException, KeyNotFoundException {
  if (anonIdNode.isTextual()) {
    String anonId = anonIdNode.textValue();
    JsonWebStructure fromCompact = JsonWebEncryption.fromCompactSerialization(anonId);
    String keyId = fromCompact.getKeyIdHeaderValue();
    PrivateKey key = keyStore.getKeyOrThrow(keyId);
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setKey(key);
    jwe.setContentEncryptionKey(key.getEncoded());
    jwe.setCompactSerialization(anonId);
    return TextNode.valueOf(jwe.getPlaintextString());
  } else if (anonIdNode.isArray()) {
    ArrayNode userIds = Json.createArrayNode();
    for (JsonNode node : anonIdNode) {
      userIds.add(decrypt(keyStore, node));
    }
    return userIds;
  } else {
    throw new IllegalArgumentException(
        "Argument to decrypt must be a TextNode or ArrayNode, but got " + anonIdNode);
  }
}
 
Example #2
Source File: HttpsJwksVerificationKeyResolverTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnEx() throws Exception
{
    String location = "https://www.example.org/";

    Get mockGet = mock(Get.class);
    when(mockGet.get(location)).thenThrow(new IOException(location + "says 'no GET for you!'"));
    HttpsJwks httpsJkws = new HttpsJwks(location);
    httpsJkws.setSimpleHttpGet(mockGet);
    HttpsJwksVerificationKeyResolver resolver = new HttpsJwksVerificationKeyResolver(httpsJkws);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
    jws.setKeyIdHeaderValue("nope");
    try
    {
        Key key = resolver.resolveKey(jws, Collections.<JsonWebStructure>emptyList());
        fail("shouldn't have resolved a key but got " + key);

    }
    catch (UnresolvableKeyException e)
    {
        log.debug("this was expected and is okay: {}", e.toString());
    }
}
 
Example #3
Source File: KeyLocationResolver.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException {
    verifyKid(jws, authContextInfo.getTokenKeyId());

    // The verificationKey may have been calculated in the constructor from the local PEM, or,
    // if authContextInfo.getTokenKeyId() is not null - from the local JWK(S) content.
    if (verificationKey != null) {
        return verificationKey;
    }

    // At this point the key can be loaded from either the HTTPS or local JWK(s) content using
    // the current token kid to select the key.
    PublicKey key = tryAsJwk(jws);

    if (key == null) {
        if (authContextInfo.getPublicKeyContent() != null) {
            throw PrincipalMessages.msg.failedToLoadPublicKeyWhileResolving();
        } else {
            throw PrincipalMessages.msg
                    .failedToLoadPublicKeyFromLocationWhileResolving(authContextInfo.getPublicKeyLocation());
        }
    }
    return key;
}
 
Example #4
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void nestedBackwards() throws Exception
{
    // a JWT that's a JWE inside a JWS, which is unusual but legal
    String jwt = "eyJjdHkiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKRlEwUklMVVZUSWl3aVpXNWpJam9pUVRFeU9FTkNReTFJVXpJMU5pSXNJbVZ3YXlJNmV5SnJkSGtpT2lKRlF5SXNJbmdpT2lKYVIwczNWbkZOUzNKV1VGcEphRXc1UkRsT05tTnpNV0ZhYlU5MVpqbHlUWGhtUm1kRFVURjFaREJuSWl3aWVTSTZJbTAyZW01VlQybEtjMnMwTlRaRVVWb3RjVTEzZEVKblpqQkRNVXh4VDB0dk5HYzNjakpGUTBkQllUZ2lMQ0pqY25ZaU9pSlFMVEkxTmlKOWZRLi4xSndRWThoVFJVczdUMFNpOWM1VE9RLkFOdUpNcFowTU1KLTBrbVdvVHhvRDlxLTA1YUxrMkpvRzMxLXdVZ01ZakdaaWZiWG96SDEzZGRuaXZpWXNtenhMcFdVNU1lQnptN3J3TExTeUlCdjB3LmVEb1lFTEhFWXBnMHFpRzBaeHUtWEE.NctFu0mNSArPnMXakIMQKagWyU4v7733dNhDNK3KwiFP2MahpfaH0LA7x0knRk0sjASRxDuEIW6UZGfPTFOjkw";

    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"HVDkXtG_j_JQUm_mNaRPSbsEhr6gdK0a6H4EURypTU0\",\"y\":\"NxdYFS2hl1w8VKf5UTpGXh2YR7KQ8gSBIHu64W0mK8M\",\"crv\":\"P-256\",\"d\":\"ToqTlgJLhI7AQYNLesI2i-08JuaYm2wxTCDiF-VxY4A\"}");
    PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"7kaETHB4U9pCdsErbjw11HGv8xcQUmFy3NMuBa_J7Os\",\"y\":\"FZK-vSMpKk9gLWC5wdFjG1W_C7vgJtdm1YfNPZevmCw\",\"crv\":\"P-256\",\"d\":\"spOxtF0qiKrrCTaUs_G04RISjCx7HEgje_I7aihXVMY\"}");

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420226222))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(2, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(0) instanceof JsonWebEncryption);
        assertTrue(joseObjects.get(1) instanceof JsonWebSignature);
    }

}
 
Example #5
Source File: SimpleJwtConsumerTestHelp.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
static void expectValidationFailure(JwtClaims jwtClaims, JwtConsumer jwtConsumer)
{
    try
    {
        jwtConsumer.validate(new JwtContext(jwtClaims, Collections.<JsonWebStructure>emptyList()));
        Assert.fail("claims validation should have thrown an exception");
    }
    catch (InvalidJwtException e)
    {
        log.debug("Expected exception: {}", e.toString());
    }
}
 
Example #6
Source File: JwtTokenVerifierImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private JsonWebStructure parse(String token) {
    try {
        return JsonWebStructure.fromCompactSerialization(token);
    } catch (JoseException e) {
        // token was not formed as JWT token. Probably it's a different kind of bearer token
        // some other plugins have introduced
        return null;
    }
}
 
Example #7
Source File: ProviderContextTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
void expectNoProviderProduce(JsonWebStructure jwx)
{
    try
    {
        String compactSerialization = jwx.getCompactSerialization();
        Assert.fail("Shouldn't have gotten compact serialization " + compactSerialization);
    }
    catch (JoseException e)
    {
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString(NO_SUCH_PROVIDER));
    }
}
 
Example #8
Source File: ProviderContextTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
void expectNoProviderConsume(JsonWebStructure jwx)
{
    try
    {
        String inside = jwx.getPayload();
        Assert.fail("Shouldn't have gotten payload " + inside);
    }
    catch (JoseException e)
    {
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString(NO_SUCH_PROVIDER));
    }
}
 
Example #9
Source File: CritHeaderTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public static void expectFail(JsonWebStructure jwx)
{
    try
    {
        jwx.getPayload();
        fail("should have failed due to crit header");
    }
    catch (JoseException e)
    {
        log.debug("Expected something like this: {}", e.toString());
    }
}
 
Example #10
Source File: SelectorSupport.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public static SimpleJwkFilter commonFilterForInbound(JsonWebStructure jwx) throws JoseException
{
    SimpleJwkFilter filter = new SimpleJwkFilter();
    String kid = jwx.getKeyIdHeaderValue();
    if (kid != null)
    {
        filter.setKid(kid, SimpleJwkFilter.VALUE_REQUIRED);
    }

    String x5t = jwx.getX509CertSha1ThumbprintHeaderValue();
    String x5tS256 = jwx.getX509CertSha256ThumbprintHeaderValue();
    filter.setAllowFallbackDeriveFromX5cForX5Thumbs(true);
    if (x5t != null)
    {
        filter.setX5t(x5t, SimpleJwkFilter.OMITTED_OKAY);
    }
    if (x5tS256 != null)
    {
        filter.setX5tS256(x5tS256, SimpleJwkFilter.OMITTED_OKAY);
    }

    String keyType = jwx.getAlgorithm().getKeyType();
    filter.setKty(keyType);
    String use = (jwx instanceof JsonWebSignature) ? Use.SIGNATURE : Use.ENCRYPTION;
    filter.setUse(use, SimpleJwkFilter.OMITTED_OKAY);
    return filter;
}
 
Example #11
Source File: JwtContext.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public JwtContext(String jwt, JwtClaims jwtClaims, List<JsonWebStructure> joseObjects)
{
    this.jwt = jwt;
    this.jwtClaims = jwtClaims;
    this.joseObjects = joseObjects;
}
 
Example #12
Source File: JwtContext.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public JwtContext(JwtClaims jwtClaims, List<JsonWebStructure> joseObjects)
{
    this.jwtClaims = jwtClaims;
    this.joseObjects = joseObjects;
}
 
Example #13
Source File: JwtConsumer.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
private boolean isNestedJwt(JsonWebStructure joseObject)
{
    String cty = joseObject.getContentTypeHeaderValue();
    return cty != null && (cty.equalsIgnoreCase("jwt") || cty.equalsIgnoreCase("application/jwt"));
}
 
Example #14
Source File: SimpleKeyResolver.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Override
public Key resolveKey(JsonWebEncryption jwe, List<JsonWebStructure> nestingContext)
{
    return key;
}
 
Example #15
Source File: SimpleKeyResolver.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Override
public Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext)
{
    return key;
}
 
Example #16
Source File: X509VerificationKeyResolver.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Override
public Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException
{
    String x5t = jws.getX509CertSha1ThumbprintHeaderValue();
    String x5tS256 = jws.getX509CertSha256ThumbprintHeaderValue();

    if (x5t == null && x5tS256 == null)
    {
        if (tryAllOnNoThumbHeader)
        {
            return attemptAll(jws);
        }
        throw new UnresolvableKeyException("Neither the " + X509_CERTIFICATE_THUMBPRINT + " header nor the " + X509_CERTIFICATE_SHA256_THUMBPRINT + " header are present in the JWS.");
    }

    X509Certificate x509Certificate = x5tMap.get(x5t);
    if (x509Certificate == null)
    {
        x509Certificate = x5tS256Map.get(x5tS256);
    }

    if (x509Certificate == null)
    {
        StringBuilder sb = new StringBuilder();

        sb.append("The X.509 Certificate Thumbprint header(s) in the JWS do not identify any of the provided Certificates -");
        if (x5t != null)
        {
            sb.append(" ").append(X509_CERTIFICATE_THUMBPRINT).append("=").append(x5t);
            sb.append(" vs. SHA-1 thumbs:").append(x5tMap.keySet());
        }

        if (x5tS256 != null)
        {
            sb.append(" ").append(X509_CERTIFICATE_SHA256_THUMBPRINT).append("=").append(x5tS256);
            sb.append(" vs. SHA-256 thumbs:").append(x5tS256Map.keySet());
        }

        sb.append(".");
        throw new UnresolvableKeyException(sb.toString());
    }

    return x509Certificate.getPublicKey();
}
 
Example #17
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void tripleNesting() throws Exception
{
    // a JWT that's a JWE inside a JWS, which is unusual but legal
    String jwt = "eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiY3R5Ijoiand0IiwicDJjIjo4MTkyLCJwMnMiOiJiWE13N0F3YUtITWZ4cWRNIn0.5Qo4mtR0E6AnTsiq-hcH9_RJoZwmWiMl0se_riEr1sdz2IXA-vCkrw.iA7lBH3Tzs4uIJVtekZEfg.jkdleffS8GIen_xt_g3QHAc0cat6UBAODpv6WLJ_ytMw-h0dtV0F77d7k1oWxBQ68Ff83v3Pxsyiqf6K9BQUVyzmI6rZafDStQm1IdTS-rvsiB4qDrx9juMqzu1udPy5N7JGs_CDV31Ky3fWEveAy4kBX46-axdyhP5XFg6xMfJ614mcf_bfo5hIJByZFwqNolNwsHLUTuiUBa4Mdg-tfob692-ox8B2c6w4RqRrLOVA_M3gENoxbLIJGL0WL1OkdQb7fyEsaMzR3urJL1t8LI5Q1pD8wjbiv4VKvc1BqoJSM0h9mLm_GNhTdQGPmevBwWVZ1k1tWJjQw0nU2eFZJi1STDGzK1GRDBD91rZSYD763WHADbxcqxrcri92jtyZrxB22pJXEgkpMlUkxqjCFATV20WSM8aSW4Od9Of9MCnrNTIby_3np4zEq5EpFEkVmH-9PzalKWo5gOHR8Zqnldyz6xcOamP34o_lEh5ddEwAFjGTlJWrDkssMeBjOog3_CXHZhutD9IfCKmIHu6Wk10XkELamiKPmNCe_CMDEdx6o6LrCtfyheOfgpDaZeZZc3Y-TF1o9J3RmCZqB-oHgLEc9mZQrGU6r5UZ4lYyfrAJl2y7Rya87LBGsUjSs7SuIyQKYkH5ek8j_9rhm_3nZhivDchkiWx5J3Pzso5Q3p6hjUfvhpgO2ywtnii45iINi5UAL6O8xqUhxZUJSoMxt1XKwx92bmC9kOoF1ljLm-w.VP_VFGef9SGdxoHCZ01FxQ";

    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"HVDkXtG_j_JQUm_mNaRPSbsEhr6gdK0a6H4EURypTU0\",\"y\":\"NxdYFS2hl1w8VKf5UTpGXh2YR7KQ8gSBIHu64W0mK8M\",\"crv\":\"P-256\",\"d\":\"ToqTlgJLhI7AQYNLesI2i-08JuaYm2wxTCDiF-VxY4A\"}");
    final PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"7kaETHB4U9pCdsErbjw11HGv8xcQUmFy3NMuBa_J7Os\",\"y\":\"FZK-vSMpKk9gLWC5wdFjG1W_C7vgJtdm1YfNPZevmCw\",\"crv\":\"P-256\",\"d\":\"spOxtF0qiKrrCTaUs_G04RISjCx7HEgje_I7aihXVMY\"}");
    final Key passwordIsTaco = new PbkdfKey("taco");

    DecryptionKeyResolver decryptionKeyResolver = new DecryptionKeyResolver()
    {
        @Override
        public Key resolveKey(JsonWebEncryption jwe, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException
        {
            return nestingContext.isEmpty() ? passwordIsTaco : encKey.getPrivateKey();
        }
    };

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKeyResolver(decryptionKeyResolver)
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKeyResolver(decryptionKeyResolver)
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420229816))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(3, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(2) instanceof JsonWebEncryption);
        assertTrue(joseObjects.get(1) instanceof JsonWebEncryption);
        assertTrue(joseObjects.get(0) instanceof JsonWebSignature);
    }

}
 
Example #18
Source File: SimpleJwtConsumerTestHelp.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
static void goodValidate(JwtClaims jwtClaims, JwtConsumer jwtConsumer) throws InvalidJwtException
{
    jwtConsumer.validate(new JwtContext(jwtClaims, Collections.<JsonWebStructure>emptyList()));
}
 
Example #19
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@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() // the JWT must have an expiration time
            .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
            .setRequireSubject() // the JWT must have a subject claim
            .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key
            .build(); // create the JwtConsumer instance

        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"));
    }
 
Example #20
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void missingCtyInNested() throws Exception
{
    // Nested jwt without "cty":"JWT" -> expect failure here as the cty is a MUST for nesting
    // setEnableLiberalContentTypeHandling() on the builder will enable a best effort to deal with the content even when cty isn't specified

    String jwt = "eyJ6aXAiOiJERUYiLCJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImVwayI6eyJrdHkiOiJFQyIsIngiOiIwRGk0VTBZQ0R2NHAtS2hETUZwUThvY0FsZzA2SEwzSHR6UldRbzlDLWV3IiwieSI6IjBfVFJjR1Y3Qy05d0xseFJZSExJOFlKTXlET2hWNW5YeHVPMGdRVmVxd0EiLCJjcnYiOiJQLTI1NiJ9fQ..xw5H8Kztd_sqzbXjt4GKUg.YNa163HLj7MwlvjzGihbOHnJ2PC3NOTnnvVOanuk1O9XFJ97pbbHHQzEeEwG6jfvDgdmlrLjcIJkSu1U8qRby7Xr4gzP6CkaDPbKwvLveETZSNdmZh37XKfnQ4LvKgiko6OQzyLYG1gc97kUOeikXTYVaYaeV1838Bi4q3DsIG-j4ZESg0-ePQesw56A80AEE3j6wXwZ4vqugPP9_ogZzkPFcHf1lt3-A4amNMjDbV8.u-JJCoakXI55BG2rz_kBlg";
    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"loF6m9WAW_GKrhoh48ctg_d78fbIsmUb02XDOwJj59c\",\"y\":\"kDCHDkCbWjeX8DjD9feQKcndJyerdsLJ4VZ5YSTWCoU\",\"crv\":\"P-256\",\"d\":\"6D1C9gJsT9KXNtTNyqgpdyQuIrK-qzo0_QJOVe9DqJg\"}");
    PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"PNbMydlpYRBFTYn_XDFvvRAFqE4e0EJmK6-zULTVERs\",\"y\":\"dyO9wGVgKS3gtP5bx0PE8__MOV_HLSpiwK-mP1RGZgk\",\"crv\":\"P-256\",\"d\":\"FIs8wVojHBdl7vkiZVnLBPw5S9lbn4JF2WWY1OTupic\"}");

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .setEnableLiberalContentTypeHandling()
            .build();

    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219088))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);

    consumer = new JwtConsumerBuilder()
            .setEnableLiberalContentTypeHandling()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219088))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(2, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(0) instanceof JsonWebSignature);
        assertTrue(joseObjects.get(1) instanceof JsonWebEncryption);
    }
}
 
Example #21
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void missingCtyInNestedViaNimbusExample() throws Exception
{
    // "Signed and encrypted JSON Web Token (JWT)" example JWT made from http://connect2id.com/products/nimbus-jose-jwt/examples/signed-and-encrypted-jwt
    // didn't have "cty":"JWT" at the time of writing (1/5/15 - https://twitter.com/__b_c/status/552105927512301568) but it made me think
    // allowing more liberal processing might be a good idea
    // keys and enc alg were changed from the example to produce this jwt
    final String jwt =
            "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0." +
            "IAseIHBLnv7hFKz_V3-o-Of3Mf2DIGzFnSh_8sLZgujPaNIG8NlZmA." +
            "fwbuvibqYUlDzTXTtsB6yw." +
            "5T70ZVMqOTl4q_tYegL0bgJpT2wTUlSvnJ2QAB8KfpNO_J3StiK8oHvSmVOPOrCQJai_XffZGUpmAO2fnGnUajKmQpxm_iaJUZtzexwqeNlVzAr-swLUZDmW0lh3NgDB" +
                "EAgY4khN7v1L_etToKuuEI6P-UGsg34BqaNuZEkj7ylsY1McZg73t5x9C4Q9dsBbsPLFPPUxxvA2abJhAq1Hew." +
            "D1hDq8pD6nQ42yvez-yjlQ\n";

    AesKey decryptionKey = new AesKey(new byte[16]);

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(decryptionKey)
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .setEnableLiberalContentTypeHandling()
            .build();

    JwtContext jwtContext = firstPassConsumer.process(jwt);

    final JwtConsumer consumer = new JwtConsumerBuilder()
            .setEnableLiberalContentTypeHandling() // this will try nested content as JOSE if JSON paring fails
            .setDecryptionKey(decryptionKey)
            .setVerificationKey(new AesKey(new byte[32]))
            .setEvaluationTime(NumericDate.fromSeconds(1420467806))
            .setExpectedIssuer("https://c2id.com")
            .setRequireIssuedAt()
            .build();

    JwtContext ctx = consumer.process(jwt);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("alice", equalTo(jwtClaims.getSubject()));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(2, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(0) instanceof JsonWebSignature);
        assertTrue(joseObjects.get(1) instanceof JsonWebEncryption);
    }
}
 
Example #22
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void ctyRoundTrip() throws JoseException, InvalidJwtException, MalformedClaimException
{
    JsonWebKeySet jwks = new JsonWebKeySet("{\"keys\":[" +
            "{\"kty\":\"oct\",\"kid\":\"hk1\",\"alg\":\"HS256\",\"k\":\"RYCCH0Qai_7Clk_GnfBElTFIa5VJP3pJUDd8g5H0PKs\"}," +
            "{\"kty\":\"oct\",\"kid\":\"ek1\",\"alg\":\"A128KW\",\"k\":\"Qi38jqNMENlgKaVRbhKWnQ\"}]}");

    SimpleJwkFilter filter = new SimpleJwkFilter();
    filter.setKid("hk1", false);
    JsonWebKey hmacKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    filter = new SimpleJwkFilter();
    filter.setKid("ek1", false);
    JsonWebKey encKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    JwtClaims claims = new JwtClaims();
    claims.setSubject("subject");
    claims.setAudience("audience");
    claims.setIssuer("issuer");
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setNotBeforeMinutesInThePast(5);
    claims.setGeneratedJwtId();

    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload(claims.toJson());
    jws.setKey(hmacKey.getKey());
    jws.setKeyIdHeaderValue(hmacKey.getKeyId());
    String innerJwt = jws.getCompactSerialization();

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A128KW);
    jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
    jwe.setKey(encKey.getKey());
    jwe.setKeyIdHeaderValue(encKey.getKeyId());
    jwe.setContentTypeHeaderValue("JWT");
    jwe.setPayload(innerJwt);
    String jwt = jwe.getCompactSerialization();

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setExpectedIssuer("issuer")
            .setExpectedAudience("audience")
            .setRequireSubject()
            .setRequireExpirationTime()
            .setDecryptionKey(encKey.getKey())
            .setVerificationKey(hmacKey.getKey())
            .build();

    JwtContext jwtContext = jwtConsumer.process(jwt);
    Assert.assertThat("subject", equalTo(jwtContext.getJwtClaims().getSubject()));
    List<JsonWebStructure> joseObjects = jwtContext.getJoseObjects();
    JsonWebStructure outerJsonWebObject = joseObjects.get(joseObjects.size() - 1);
    Assert.assertTrue(outerJsonWebObject instanceof JsonWebEncryption);
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getContentTypeHeaderValue()));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeader(HeaderParameterNames.CONTENT_TYPE)));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeaders().getStringHeaderValue(HeaderParameterNames.CONTENT_TYPE)));
    JsonWebStructure innerJsonWebObject = joseObjects.get(0);
    Assert.assertTrue(innerJsonWebObject instanceof JsonWebSignature);
}
 
Example #23
Source File: DecryptionKeyResolver.java    From Jose4j with Apache License 2.0 2 votes vote down vote up
/**
 * Choose the key to be used for decryption on the given JWE.
 * @param jwe the JsonWebEncryption that's about to be decrypted
 * @param nestingContext a list of JOSE objects, if any, in which the JWE was nested.
 *                       The last item in the list is the outer most JOSE object (not including the current JWE).
 * @return the decryption key
 * @throws UnresolvableKeyException if no appropriate key can be found
 */
Key resolveKey(JsonWebEncryption jwe, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException;
 
Example #24
Source File: VerificationKeyResolver.java    From Jose4j with Apache License 2.0 2 votes vote down vote up
/**
 * Choose the key to be used for signature verification on the given JWS.
 * @param jws the JsonWebSignature that's about to be verified
 * @param nestingContext a list of JOSE objects, if any, in which the JWS was nested.
 *                       The last item in the list is the outer most JOSE object (not including the current JWS).
 * @return the signature or MAC verification key
 * @throws UnresolvableKeyException if no appropriate key can be found
 */
Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException;
 
Example #25
Source File: JweCustomizer.java    From Jose4j with Apache License 2.0 2 votes vote down vote up
/**
 * Customize the JsonWebEncryption
 * @param jwe the JsonWebEncryption that can be customized prior to decryption
 * @param nestingContext a list of JOSE objects, if any, in which the JWE was nested.
 *                       The last item in the list is the outer most JOSE object (not including the current JWE).
 */
void customize(JsonWebEncryption jwe, List<JsonWebStructure> nestingContext);
 
Example #26
Source File: JwtContext.java    From Jose4j with Apache License 2.0 2 votes vote down vote up
/**
 * All of the JOSE objects that comprise the JWT. When the JWT is nested,
 * the first item in the list is the inner most JOSE object.
 * @return the list of JOSE objects that comprise the JWT
 */
public List<JsonWebStructure> getJoseObjects()
{
    return joseObjects;
}
 
Example #27
Source File: JwsCustomizer.java    From Jose4j with Apache License 2.0 2 votes vote down vote up
/**
 * Customize the JsonWebSignature
 * @param jws the JsonWebSignature that can be customized prior to signature verification.
 * @param nestingContext a list of JOSE objects, if any, in which the JWS was nested.
 *                       The last item in the list is the outer most JOSE object (not including the current JWS).
 */
void customize(JsonWebSignature jws, List<JsonWebStructure> nestingContext);
 
Example #28
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 2 votes vote down vote up
@Test
    public void getToken() throws Exception {
        j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

        User user = User.get("alice");
        user.setFullName("Alice Cooper");
        user.addProperty(new Mailer.UserProperty("[email protected]"));

        JenkinsRule.WebClient webClient = j.createWebClient();

        webClient.login("alice");

        String token = getToken(webClient);

        Assert.assertNotNull(token);

        JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);

        Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);

        JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;

        System.out.println(token);
        System.out.println(jsw.toString());


        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());
        System.out.println(jsonObject.toString());
        RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null);

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime() // the JWT must have an expiration time
            .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
            .setRequireSubject() // the JWT must have a subject claim
            .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key
            .build(); // create the JwtConsumer instance

        JwtClaims claims = jwtConsumer.processToClaims(token);
        Assert.assertEquals("alice",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("alice", userContext.get("id"));
        Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
        Assert.assertEquals("[email protected]", userContext.get("email"));
    }