Java Code Examples for org.jose4j.jwt.JwtClaims#parse()

The following examples show how to use org.jose4j.jwt.JwtClaims#parse() . 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: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void someBasicJtiChecks() throws InvalidJwtException
{
    JwtClaims jwtClaims = JwtClaims.parse("{\"jti\":\"1Y5iLSQfNgcSGt0A4is29\"}");
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setRequireJwtId().build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"notjti\":\"lbZ_mLS6w3xBSlvW6ULmkV-uLCk\"}");
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"jti\":55581529751992}");
    jwtConsumer = new JwtConsumerBuilder().setRequireJwtId().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"jti\":[\"S0w3XbslvW6ULmk0\", \"5iLSQfNgcSGt7A4is\"]}");
    jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
}
 
Example 2
Source File: JwtSignTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private void doTestSignedExistingClaims(String jwt) throws Exception {

        JsonWebSignature jws = getVerifiedJws(jwt);
        JwtClaims claims = JwtClaims.parse(jws.getPayload());

        Assert.assertEquals(9, claims.getClaimsMap().size());
        checkDefaultClaimsAndHeaders(getJwsHeaders(jwt, 2), claims, "RS256", 1000);

        Assert.assertEquals("https://server.example.com", claims.getIssuer());
        Assert.assertEquals("a-123", claims.getClaimValue("jti"));
        Assert.assertEquals("24400320", claims.getSubject());
        Assert.assertEquals("[email protected]", claims.getClaimValue("upn"));
        Assert.assertEquals("jdoe", claims.getClaimValue("preferred_username"));
        Assert.assertEquals("s6BhdRkqt3", claims.getAudience().get(0));
        Assert.assertEquals(1311281970L, claims.getExpirationTime().getValue());
        Assert.assertEquals(1311280970L, claims.getIssuedAt().getValue());
        Assert.assertEquals(1311280969, claims.getClaimValue("auth_time", Long.class).longValue());
    }
 
Example 3
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void someBasicSubChecks() throws InvalidJwtException
{
    JwtClaims jwtClaims = JwtClaims.parse("{\"sub\":\"brian.d.campbell\"}");
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setRequireSubject().build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"name\":\"brian.d.campbell\"}");
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"sub\":724729}");
    jwtConsumer = new JwtConsumerBuilder().setRequireSubject().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"sub\":{\"values\":[\"one\", \"2\"]}}");
    jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
}
 
Example 4
Source File: OpenIDConnectAuthenticator.java    From java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isExpired(Map<String, Object> config) {
  String idToken = (String) config.get(OIDC_ID_TOKEN);

  if (idToken == null) {
    return true;
  } else {
    JsonWebSignature jws = new JsonWebSignature();
    try {
      jws.setCompactSerialization(idToken);
      // we don't care if its valid or not cryptographicly as the only way to verify is to query
      // the remote identity provider's configuration url which is the same chanel as the token
      // request.  If there is a malicious proxy there's no way for the client to know.  Also,
      // the client doesn't need to trust the, token, only bear it to the server which will verify
      // it.

      String jwt = jws.getUnverifiedPayload();
      JwtClaims claims = JwtClaims.parse(jwt);

      // expired now is >= expiration AND exp is present
      return claims.getExpirationTime() == null
          || NumericDate.now().isOnOrAfter(claims.getExpirationTime());
    } catch (JoseException | InvalidJwtException | MalformedClaimException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 5
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void someBasicChecks() throws InvalidJwtException
{
    JwtClaims jcs = JwtClaims.parse("{\"sub\":\"subject\", \"iss\":\"issuer\", \"aud\":\"audience\"}");
    JwtConsumer consumer = new JwtConsumerBuilder().setExpectedAudience("audience").setExpectedIssuer("issuer").build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);

    consumer = new JwtConsumerBuilder()
            .setExpectedAudience("nope")
            .setExpectedIssuer("no way")
            .setRequireSubject()
            .setRequireJwtId()
            .build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
}
 
Example 6
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void someBasicIssChecks() throws InvalidJwtException
{
    JwtClaims jwtClaims = JwtClaims.parse("{\"iss\":\"issuer.example.com\"}");
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(null).build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(false, null).build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer("issuer.example.com").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(false, "issuer.example.com").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer("nope.example.com").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"sub\":\"subject\"}");
    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer("issuer.example.com").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(false, "issuer.example.com").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(false, null).build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"iss\":[\"issuer1\", \"other.one\", \"meh\"]}");
    jwtConsumer = new JwtConsumerBuilder().setExpectedIssuer("issuer.example.com").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"iss\":[\"issuer1\", \"nope.not\"]}");
    jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
}
 
Example 7
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
private static JwtClaims createJwtClaims(String jsonResName, Set<InvalidClaims> invalidClaims,
        Map<String, Long> timeClaims) throws Exception {
    
    String content = readJsonContent(jsonResName);
    JwtClaims claims = JwtClaims.parse(content);

    // Change the issuer to INVALID_ISSUER for failure testing if requested
    if (invalidClaims.contains(InvalidClaims.ISSUER)) {
        claims.setIssuer("INVALID_ISSUER");
    }
    long currentTimeInSecs = currentTimeInSecs();
    long exp = currentTimeInSecs + 300;
    long iat = currentTimeInSecs;
    long authTime = currentTimeInSecs;
    boolean expWasInput = false;
    // Check for an input exp to override the default of now + 300 seconds
    if (timeClaims != null && timeClaims.containsKey(Claims.exp.name())) {
        exp = timeClaims.get(Claims.exp.name());
        expWasInput = true;
    }
    // iat and auth_time should be before any input exp value
    if (expWasInput) {
        iat = exp - 5;
        authTime = exp - 5;
    }
    claims.setIssuedAt(NumericDate.fromSeconds(iat));
    claims.setClaim(Claims.auth_time.name(), authTime);
    // If the exp claim is not updated, it will be an old value that should be seen as expired
    if (!invalidClaims.contains(InvalidClaims.EXP)) {
        claims.setExpirationTime(NumericDate.fromSeconds(exp));
    }
    // Return the token time values if requested
    if (timeClaims != null) {
        timeClaims.put(Claims.iat.name(), iat);
        timeClaims.put(Claims.auth_time.name(), authTime);
        timeClaims.put(Claims.exp.name(), exp);
    }
    return claims;
}
 
Example 8
Source File: JwtBuildUtils.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
static JwtClaims parseJwtClaims(String jwtLocation) {
    try {
        return JwtClaims.parse(readJsonContent(jwtLocation));
    } catch (Exception ex) {
        throw ImplMessages.msg.failureToParseJWTClaims(ex.getMessage(), ex);
    }
}
 
Example 9
Source File: JwtClaimShortcutsTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private static void verifyJwtWithArray(String jwt, String customClaim, String customValue) throws Exception {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setKey(KeyUtils.readPublicKey("/publicKey.pem"));
    jws.setCompactSerialization(jwt);
    Assert.assertTrue(jws.verifySignature());
    JwtClaims claims = JwtClaims.parse(jws.getPayload());
    Assert.assertEquals(4, claims.getClaimsMap().size());
    @SuppressWarnings("unchecked")
    List<String> list = (List<String>) claims.getClaimValue(customClaim);
    Assert.assertEquals(1, list.size());
    Assert.assertEquals(customValue, list.get(0));
    Assert.assertNotNull(claims.getIssuedAt());
    Assert.assertNotNull(claims.getExpirationTime());
    Assert.assertNotNull(claims.getJwtId());
}
 
Example 10
Source File: TokenHelper.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
public static User parseToken(@NotNull JsonWebEncryption jwe, @NotNull String token, int tokenEnsureTime) {
  try {
    jwe.setCompactSerialization(token);
    final JwtClaims claims = JwtClaims.parse(jwe.getPayload());
    final NumericDate now = NumericDate.now();
    final NumericDate expire = NumericDate.fromMilliseconds(now.getValueInMillis());
    if (tokenEnsureTime > 0) {
      expire.addSeconds(tokenEnsureTime);
    }
    if (claims.getExpirationTime() == null || claims.getExpirationTime().isBefore(expire)) {
      return null;
    }
    if (claims.getNotBefore() == null || claims.getNotBefore().isAfter(now)) {
      return null;
    }
    if (claims.getSubject() == null) {
      return User.getAnonymous();
    }
    return User.create(
        claims.getSubject(),
        claims.getClaimValue("name", String.class),
        claims.getClaimValue("email", String.class),
        claims.getClaimValue("external", String.class),
        UserType.valueOf(claims.getClaimValue("type", String.class)),
        null
    );
  } catch (JoseException | MalformedClaimException | InvalidJwtException e) {
    log.warn("Token parsing error: " + e.getMessage());
    return null;
  }
}
 
Example 11
Source File: JwtClaimShortcutsTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private static void verifyJwt(String jwt, String customClaim, String customValue) throws Exception {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setKey(KeyUtils.readPublicKey("/publicKey.pem"));
    jws.setCompactSerialization(jwt);
    Assert.assertTrue(jws.verifySignature());
    JwtClaims claims = JwtClaims.parse(jws.getPayload());
    Assert.assertEquals(4, claims.getClaimsMap().size());
    Assert.assertEquals(customValue, claims.getClaimValue(customClaim));
    Assert.assertNotNull(claims.getIssuedAt());
    Assert.assertNotNull(claims.getExpirationTime());
    Assert.assertNotNull(claims.getJwtId());
}
 
Example 12
Source File: JwtSignTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private void verifySignedJsonObject(String jwt) throws Exception {
    JsonWebSignature jws = getVerifiedJws(jwt);
    JwtClaims claims = JwtClaims.parse(jws.getPayload());

    Assert.assertEquals(5, claims.getClaimsMap().size());
    checkDefaultClaimsAndHeaders(getJwsHeaders(jwt, 2), claims);

    Assert.assertEquals("Alice", claims.getClaimValue("username"));
    @SuppressWarnings("unchecked")
    Map<String, String> address = (Map<String, String>) claims.getClaimValue("address");
    Assert.assertEquals(2, address.size());
    Assert.assertEquals("someCity", address.get("city"));
    Assert.assertEquals("someStreet", address.get("street"));
}
 
Example 13
Source File: JwtSignTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignMapOfClaimsShortcut() throws Exception {
    String jwt = Jwt.sign(Collections.singletonMap("customClaim", "custom-value"));

    JsonWebSignature jws = getVerifiedJws(jwt);
    JwtClaims claims = JwtClaims.parse(jws.getPayload());

    Assert.assertEquals(4, claims.getClaimsMap().size());
    checkDefaultClaimsAndHeaders(getJwsHeaders(jwt, 2), claims);

    Assert.assertEquals("custom-value", claims.getClaimValue("customClaim"));
}
 
Example 14
Source File: JwtCallerPrincipalUnitTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testAllClaims() throws InvalidJwtException {
    InputStream is = getClass().getResourceAsStream("/Token1.json");
    JsonObject content = Json.createReader(is).readObject();
    JwtClaims jwtClaims = JwtClaims.parse(content.toString());
    DefaultJWTCallerPrincipal principal = new DefaultJWTCallerPrincipal(jwtClaims);

    String iss = principal.getIssuer();
    Assertions.assertEquals("https://server.example.com", iss);
    String jti = principal.getTokenID();
    Assertions.assertEquals("a-123", jti);
    String name = principal.getName();
    Assertions.assertEquals("[email protected]", name);
    String upn = principal.getClaim(Claims.upn.name());
    Assertions.assertEquals("[email protected]", upn);
    Set<String> aud = principal.getAudience();
    Assertions.assertEquals(new HashSet<>(Arrays.asList("s6BhdRkqt3")), aud);
    Long exp = principal.getExpirationTime();
    Assertions.assertEquals(1311281970l, exp.longValue());
    Long iat = principal.getIssuedAtTime();
    Assertions.assertEquals(1311280970l, iat.longValue());
    String sub = principal.getSubject();
    Assertions.assertEquals("24400320", sub);
    Set<String> groups = principal.getGroups();
    String[] expectedGroups = { "Echoer",
            "Tester",
            "group1",
            "group2" };
    Assertions.assertEquals(new HashSet<String>(Arrays.asList(expectedGroups)), groups);

    /*
     * "customDoubleArray": [0.1, 1.1, 2.2, 3.3, 4.4],
     */
    JsonArray customDoubleArray = principal.getClaim("customDoubleArray");
    Assertions.assertEquals(5, customDoubleArray.size());
    Assertions.assertEquals(Json.createValue(0.1), customDoubleArray.getJsonNumber(0));
    Assertions.assertEquals(Json.createValue(1.1), customDoubleArray.getJsonNumber(1));
    Assertions.assertEquals(Json.createValue(2.2), customDoubleArray.getJsonNumber(2));
    Assertions.assertEquals(Json.createValue(3.3), customDoubleArray.getJsonNumber(3));
    Assertions.assertEquals(Json.createValue(4.4), customDoubleArray.getJsonNumber(4));

    // "customString": "customStringValue",
    Assertions.assertEquals("customStringValue", principal.getClaim("customString"));
    // "customInteger": 123456789,
    JsonNumber customInteger = principal.getClaim("customInteger");
    Assertions.assertEquals(Json.createValue(123456789), customInteger);
    // "customDouble": 3.141592653589793,
    JsonNumber customDouble = principal.getClaim("customDouble");
    Assertions.assertEquals(Json.createValue(3.141592653589793), customDouble);

    /*
     * "customStringArray": ["value0", "value1", "value2" ],
     */
    JsonArray customStringArray = principal.getClaim("customStringArray");
    Assertions.assertEquals(3, customStringArray.size());
    Assertions.assertEquals(Json.createValue("value0"), customStringArray.getJsonString(0));
    Assertions.assertEquals(Json.createValue("value1"), customStringArray.getJsonString(1));
    Assertions.assertEquals(Json.createValue("value2"), customStringArray.getJsonString(2));
    /* "customIntegerArray": [0,1,2,3] */
    JsonArray customIntegerArray = principal.getClaim("customIntegerArray");
    Assertions.assertEquals(4, customIntegerArray.size());
    Assertions.assertEquals(Json.createValue(0), customIntegerArray.getJsonNumber(0));
    Assertions.assertEquals(Json.createValue(1), customIntegerArray.getJsonNumber(1));
    Assertions.assertEquals(Json.createValue(2), customIntegerArray.getJsonNumber(2));
    Assertions.assertEquals(Json.createValue(3), customIntegerArray.getJsonNumber(3));

    /*
     * "customObject": {
     * "my-service": {
     * "groups": [
     * "group1",
     * "group2"
     * ],
     * "roles": [
     * "role-in-my-service"
     * ]
     * },
     * "service-B": {
     * "roles": [
     * "role-in-B"
     * ]
     * },
     * "service-C": {
     * "groups": [
     * "groupC",
     * "web-tier"
     * ]
     * }
     * }
     */
    JsonObject customObject = principal.getClaim("customObject");
    String[] keys = { "my-service", "service-B", "service-C" };
    Assertions.assertEquals(new HashSet<>(Arrays.asList(keys)), customObject.keySet());
}
 
Example 15
Source File: JwtHelperTest.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testVerifyJwtByJsonWebKeys() throws Exception {
    Map<String, Object> secretConfig = Config.getInstance().getJsonMapConfig(JwtIssuer.SECRET_CONFIG);
    JwtConfig jwtConfig = (JwtConfig) Config.getInstance().getJsonObjectConfig(JwtIssuer.JWT_CONFIG, JwtConfig.class);

    String fileName = jwtConfig.getKey().getFilename();
    String alias = jwtConfig.getKey().getKeyName();

    KeyStore ks = loadKeystore(fileName, (String)secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD));
    Key privateKey = ks.getKey(alias, ((String) secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD)).toCharArray());

    JsonWebSignature jws = new JsonWebSignature();

    String iss = "my.test.iss";
    JwtClaims jwtClaims = JwtClaims.parse("{\n" +
            "  \"sub\": \"5745ed4b-0158-45ff-89af-4ce99bc6f4de\",\n" +
            "  \"iss\": \"" + iss  +"\",\n" +
            "  \"subject_type\": \"client-id\",\n" +
            "  \"exp\": 1557419531,\n" +
            "  \"iat\": 1557419231,\n" +
            "  \"scope\": [\n" +
            "    \"my.test.scope.read\",\n" +
            "    \"my.test.scope.write\",\n" +
            "  ],\n" +
            "  \"consumer_application_id\": \"389\",\n" +
            "  \"request_transit\": \"63092\"\n" +
            "}");

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(jwtClaims.toJson());

    // use private key to sign the JWT
    jws.setKey(privateKey);

    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt = jws.getCompactSerialization();

    Assert.assertNotNull(jwt);

    System.out.print("JWT = " + jwt);

    JwtClaims claims = JwtHelper.verifyJwt(jwt, true, true, (kId, isToken) -> {
        try {
            // use public key to create the the JsonWebKey
            Key publicKey = ks.getCertificate(alias).getPublicKey();
            PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(publicKey);
            List<JsonWebKey> jwkList = Arrays.asList(jwk);
            return new JwksVerificationKeyResolver(jwkList);
        } catch (JoseException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
    });

    Assert.assertNotNull(claims);
    Assert.assertEquals(iss, claims.getStringClaimValue("iss"));
}
 
Example 16
Source File: JwtVerifierTest.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testVerifyJwtByJsonWebKeys() throws Exception {
    Map<String, Object> secretConfig = Config.getInstance().getJsonMapConfig(JwtIssuer.SECRET_CONFIG);
    JwtConfig jwtConfig = (JwtConfig) Config.getInstance().getJsonObjectConfig(JwtIssuer.JWT_CONFIG, JwtConfig.class);

    String fileName = jwtConfig.getKey().getFilename();
    String alias = jwtConfig.getKey().getKeyName();

    KeyStore ks = loadKeystore(fileName, (String)secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD));
    Key privateKey = ks.getKey(alias, ((String) secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD)).toCharArray());

    JsonWebSignature jws = new JsonWebSignature();

    String iss = "my.test.iss";
    JwtClaims jwtClaims = JwtClaims.parse("{\n" +
            "  \"sub\": \"5745ed4b-0158-45ff-89af-4ce99bc6f4de\",\n" +
            "  \"iss\": \"" + iss  +"\",\n" +
            "  \"subject_type\": \"client-id\",\n" +
            "  \"exp\": 1557419531,\n" +
            "  \"iat\": 1557419231,\n" +
            "  \"scope\": [\n" +
            "    \"my.test.scope.read\",\n" +
            "    \"my.test.scope.write\",\n" +
            "  ],\n" +
            "  \"consumer_application_id\": \"389\",\n" +
            "  \"request_transit\": \"63092\"\n" +
            "}");

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(jwtClaims.toJson());

    // use private key to sign the JWT
    jws.setKey(privateKey);

    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt = jws.getCompactSerialization();

    Assert.assertNotNull(jwt);

    System.out.print("JWT = " + jwt);

    JwtVerifier jwtVerifier = new JwtVerifier(Config.getInstance().getJsonMapConfig(CONFIG_NAME));
    JwtClaims claims = jwtVerifier.verifyJwt(jwt, true, true, (kId, isToken) -> {
        try {
            // use public key to create the the JsonWebKey
            Key publicKey = ks.getCertificate(alias).getPublicKey();
            PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(publicKey);
            List<JsonWebKey> jwkList = Arrays.asList(jwk);
            return new JwksVerificationKeyResolver(jwkList);
        } catch (JoseException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
    });

    Assert.assertNotNull(claims);
    Assert.assertEquals(iss, claims.getStringClaimValue("iss"));
}
 
Example 17
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void someBasicAudChecks() throws InvalidJwtException
{
    JwtClaims jwtClaims = JwtClaims.parse("{\"aud\":\"example.com\"}");

    JwtConsumer jwtConsumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.com").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);
    

    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org", "example.com", "k8HiI26Y7").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org", "nope", "nada").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"sub\":\"subject\"}");
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience(false, "example.org", "www.example.org").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience(true, "example.org", "www.example.org").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"aud\":[\"example.com\", \"usa.org\", \"ca.ca\"]}");
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org", "some.other.junk").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("usa.org").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("ca.ca").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("ca.ca", "some.other.thing").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("noway", "ca.ca", "some.other.thing").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("usa.org", "ca.ca", "random").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("usa.org", "ca.ca").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("usa.org", "ca.ca", "example.com").build();
    SimpleJwtConsumerTestHelp.goodValidate(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"aud\":[\"example.com\", 47, false]}");
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"aud\":20475}");
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);

    jwtClaims = JwtClaims.parse("{\"aud\":{\"aud\":\"example.org\"}}");
    jwtConsumer = new JwtConsumerBuilder().setExpectedAudience("example.org").build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jwtClaims, jwtConsumer);
}
 
Example 18
Source File: JwtEncryptTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
private void doTestEncryptedClaims(String jweCompact) throws Exception {
    checkRsaEncJweHeaders(jweCompact);
    JsonWebEncryption jwe = getJsonWebEncryption(jweCompact);
    JwtClaims claims = JwtClaims.parse(jwe.getPlaintextString());
    checkJwtClaims(claims);
}
 
Example 19
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void someBasicTimeChecks() throws InvalidJwtException, MalformedClaimException
{
    JwtClaims jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\"}");
    JwtConsumer consumer = new JwtConsumerBuilder().build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireIssuedAt().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireNotBefore().build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);


    jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"exp\":1430602000}");
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602000)).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602000)).setAllowedClockSkewInSeconds(10).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromSeconds(1430601000)).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430601000)).setAllowedClockSkewInSeconds(6000).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromSeconds(1430602002)).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602002)).setAllowedClockSkewInSeconds(1).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602002)).setAllowedClockSkewInSeconds(2).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602002)).setAllowedClockSkewInSeconds(3).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromSeconds(1430602065)).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602065)).setAllowedClockSkewInSeconds(60).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602065)).setAllowedClockSkewInSeconds(120).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);


    jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"nbf\":1430602000}");
    consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromSeconds(1430602000)).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromSeconds(1430601999)).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromSeconds(1430601983)).setAllowedClockSkewInSeconds(30).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromSeconds(1430601983)).setAllowedClockSkewInSeconds(3000).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);

    jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"nbf\":1430602000, \"iat\":1430602060, \"exp\":1430602600 }");
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setRequireNotBefore().setRequireIssuedAt().setEvaluationTime(NumericDate.fromSeconds(1430602002)).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);

    jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"nbf\":1430603000, \"iat\":1430602060, \"exp\":1430602600 }");
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602002)).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);


    jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"nbf\":1430602000, \"iat\":1430602660, \"exp\":1430602600 }");
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430602002)).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);


    jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"exp\":1430607201}");
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430600000)).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430600000)).setMaxFutureValidityInMinutes(90).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430600000)).setMaxFutureValidityInMinutes(120).build();
    SimpleJwtConsumerTestHelp.expectValidationFailure(jcs, consumer);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setEvaluationTime(NumericDate.fromSeconds(1430600000)).setMaxFutureValidityInMinutes(120).setAllowedClockSkewInSeconds(20).build();
    SimpleJwtConsumerTestHelp.goodValidate(jcs, consumer);
}
 
Example 20
Source File: JwtSignEncryptTest.java    From smallrye-jwt with Apache License 2.0 3 votes vote down vote up
private void checkRsaInnerSignedEncryptedClaims(String jweCompact, String keyEncAlgo) throws Exception {
    checkJweHeaders(jweCompact, keyEncAlgo, null);

    JsonWebEncryption jwe = getJsonWebEncryption(jweCompact);

    String jwtCompact = jwe.getPlaintextString();

    JsonWebSignature jws = getVerifiedJws(jwtCompact);
    JwtClaims claims = JwtClaims.parse(jws.getPayload());

    Assert.assertEquals(4, claims.getClaimsMap().size());
    checkClaimsAndJwsHeaders(jwtCompact, claims, "RS256", null);

    Assert.assertEquals("custom-value", claims.getClaimValue("customClaim"));
}