org.jose4j.jwt.consumer.InvalidJwtException Java Examples

The following examples show how to use org.jose4j.jwt.consumer.InvalidJwtException. 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: JwtClaimsTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetClaimsMap() throws InvalidJwtException, MalformedClaimException
{
    String json = "{\"sub\":\"subject\",\"aud\":\"audience\",\"iss\":\"issuer\"," +
            "\"jti\":\"mz3uxaCcLmQ2cwAV3oJxEQ\",\"exp\":1418906607," +
            "\"email\":\"[email protected]\", \"name\":\"Joe User\", \"someclaim\":\"yup\"}";

    JwtClaims jwtClaims = JwtClaims.parse(json);
    Map<String, Object> claimsMap = jwtClaims.getClaimsMap(INITIAL_REGISTERED_CLAIM_NAMES);
    Assert.assertThat(3, equalTo(claimsMap.size()));

    claimsMap = jwtClaims.getClaimsMap();
    Assert.assertThat(8, equalTo(claimsMap.size()));

    Collection<String> claimNames = jwtClaims.getClaimNames(INITIAL_REGISTERED_CLAIM_NAMES);
    Assert.assertThat(3, equalTo(claimNames.size()));

    claimNames = jwtClaims.getClaimNames(Collections.singleton(AUDIENCE));
    Assert.assertThat(7, equalTo(claimNames.size()));

    claimNames = jwtClaims.getClaimNames();
    Assert.assertThat(8, equalTo(claimNames.size()));

    Assert.assertThat(json, is(equalTo(jwtClaims.getRawJson())));
}
 
Example #2
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonIntegerNumericDates() throws InvalidJwtException, MalformedClaimException
{
    // JWT's NumericDate says that "non-integer values can be represented"
    // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-2
    // I always just assumed that it could only be integers (maybe b/c of the former IntDate name )
    // but looking at the text again it looks like maybe fractional values has always been possible.
    // I'm not sure I see value in truly supporting sub-second accuracy (right now, anyway) but do want to
    // ensure that we handle such values reasonably, if we receive them. This test checks that we don't fail
    // and just truncate the sub-second part.

    JwtClaims jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"nbf\":1430602000.173, \"iat\":1430602060.5, \"exp\":1430602600.77}");
    Assert.assertThat(NumericDate.fromSeconds(1430602600), equalTo(jcs.getExpirationTime()));
    Assert.assertThat(NumericDate.fromSeconds(1430602060), equalTo(jcs.getIssuedAt()));
    Assert.assertThat(NumericDate.fromSeconds(1430602000), equalTo(jcs.getNotBefore()));
}
 
Example #3
Source File: OauthHelperTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
private static boolean isTokenExpired(String authorization) {
    boolean expired = false;
    String jwt = getJwtFromAuthorization(authorization);
    if(jwt != null) {
        JwtConsumer consumer = new JwtConsumerBuilder()
                .setDisableRequireSignature()
                .setSkipSignatureVerification()
                .build();

        try {
            consumer.processToClaims(jwt);
        } catch (InvalidJwtException e) {
            if(e.hasExpired()) expired = true;
        }
    }
    return expired;
}
 
Example #4
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public static String validateEntityToken(Key key, String jwt) {

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setVerificationKey(key)
                .setRelaxVerificationKeyValidation()
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
            String subject = jwtClaims.getSubject();
            try (JsonReader reader = Json.createReader(new StringReader(subject))) {
                JsonObject subjectObject = reader.readObject(); // JsonParsingException
                return subjectObject.getString(ENTITY_KEY); // Npe
            }
        } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
            LOGGER.log(Level.FINE, "Cannot validate jwt token", e);
        }

        return null;

    }
 
Example #5
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public static String validateSharedResourceToken(Key key, String jwt) {

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setVerificationKey(key)
                .setRelaxVerificationKeyValidation()
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
            String subject = jwtClaims.getSubject();
            try (JsonReader reader = Json.createReader(new StringReader(subject))) {
                JsonObject subjectObject = reader.readObject(); // JsonParsingException
                return subjectObject.getString(SHARED_ENTITY_UUID); // Npe
            }
        } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
            LOGGER.log(Level.FINE, "Cannot validate jwt token", e);
        }

        return null;

    }
 
Example #6
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlattenClaimsOpenIdAddress() throws InvalidJwtException, MalformedClaimException
{
    String j =  // example claims from http://openid.net/specs/openid-connect-core-1_0.html OpenID Connect Core 1.0 incorporating errata set 1
            "  {\n" +
            "   \"address\": {\n" +
            "     \"street_address\": \"1234 Hollywood Blvd.\",\n" +
            "     \"locality\": \"Los Angeles\",\n" +
            "     \"region\": \"CA\",\n" +
            "     \"postal_code\": \"90210\",\n" +
            "     \"country\": \"US\"},\n" +
            "   \"phone_number\": \"+1 (310) 123-4567\"\n" +
            "  }";
    JwtClaims jcs = JwtClaims.parse(j);
    Map<String, List<Object>> claims = jcs.flattenClaims();
    for (String k : claims.keySet())
    {
        Assert.assertThat(1, equalTo(claims.get(k).size()));
    }

    Assert.assertThat("1234 Hollywood Blvd.", equalTo(claims.get("address.street_address").get(0)));
    Assert.assertThat("Los Angeles", equalTo(claims.get("address.locality").get(0)));
    Assert.assertThat("CA", equalTo(claims.get("address.region").get(0)));
    Assert.assertThat("90210", equalTo(claims.get("address.postal_code").get(0)));
    Assert.assertThat("US", equalTo(claims.get("address.country").get(0)));
    Assert.assertThat("+1 (310) 123-4567", equalTo(claims.get("phone_number").get(0)));
}
 
Example #7
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetExpirationTimeMinutesInTheFuturePartOfMinute() throws InvalidJwtException, MalformedClaimException
{
    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setExpirationTimeMinutesInTheFuture(0.167f);
    jwtClaims = JwtClaims.parse(jwtClaims.toJson());
    NumericDate expirationTime = jwtClaims.getExpirationTime();
    NumericDate checker = NumericDate.now();
    Assert.assertTrue(checker.isBefore(expirationTime));
    checker.addSeconds(9);
    Assert.assertTrue(checker.isBefore(expirationTime));
    checker.addSeconds(2);
    Assert.assertFalse(checker.isBefore(expirationTime));
}
 
Example #8
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithHelpers() throws InvalidJwtException, MalformedClaimException
{
    JwtClaims claims = new JwtClaims();
    claims.setSubject("subject");
    claims.setAudience("audience");
    claims.setIssuer("issuer");
    claims.setGeneratedJwtId();
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(5);
    String jsonClaims = claims.toJson();

    Assert.assertThat(jsonClaims, containsString("\"iss\":\"issuer\""));
    Assert.assertThat(jsonClaims, containsString("\"aud\":\"audience\""));
    Assert.assertThat(jsonClaims, containsString("\"sub\":\"subject\""));
    Assert.assertThat(jsonClaims, containsString("\"jti\":\""));
    Assert.assertThat(jsonClaims, containsString("\"exp\":"));
    Assert.assertThat(jsonClaims, containsString("\"iat\":"));
    Assert.assertThat(jsonClaims, containsString("\"nbf\":"));

    JwtClaims parsedClaims = JwtClaims.parse(jsonClaims);

    Assert.assertThat(DEFAULT_JTI_LENGTH, equalTo(parsedClaims.getJwtId().length()));

    long nowMillis = System.currentTimeMillis();

    long nbfMillis = parsedClaims.getNotBefore().getValueInMillis();
    Assert.assertTrue(nbfMillis <= (nowMillis - 300000));
    Assert.assertTrue(nbfMillis > (nowMillis - 302000));

    final long iatMIllis = parsedClaims.getIssuedAt().getValueInMillis();
    Assert.assertTrue(iatMIllis < (nowMillis + 100));
    Assert.assertTrue((nowMillis - 2000) < iatMIllis);


    final long expMillis = parsedClaims.getExpirationTime().getValueInMillis();
    Assert.assertTrue(expMillis > (nowMillis + 598000));
    Assert.assertTrue(expMillis < (nowMillis + 600000));
}
 
Example #9
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 #10
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetIat() throws InvalidJwtException, MalformedClaimException
{
    long nbf = 1418823119;
    JwtClaims claims = JwtClaims.parse("{\"iat\":" + nbf + "}");
    Assert.assertThat(nbf, equalTo(claims.getIssuedAt().getValue()));
}
 
Example #11
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNbf() throws InvalidJwtException, MalformedClaimException
{
    long nbf = 1418823109;
    JwtClaims claims = JwtClaims.parse("{\"nbf\":" + nbf + "}");
    Assert.assertThat(nbf, equalTo(claims.getNotBefore().getValue()));
}
 
Example #12
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAudienceSingleInArray() throws InvalidJwtException, MalformedClaimException
{
    JwtClaims claims = JwtClaims.parse("{\"aud\":[\"one\"]}");
    List<String> audiences = claims.getAudience();
    Assert.assertThat(1, equalTo(audiences.size()));
    Assert.assertThat("one", equalTo(audiences.get(0)));
}
 
Example #13
Source File: TestTokenRequiredClaims.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void missingRequiredClaims() throws Exception {
    String token = TokenUtils.generateTokenString("/Token1.json");
    PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
    contextInfo.setRequiredClaims(Stream.of("something", "else").collect(toSet()));
    JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();

    final ParseException exception = assertThrows(ParseException.class, () -> factory.parse(token, contextInfo));
    assertTrue(exception.getCause() instanceof InvalidJwtException);
}
 
Example #14
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAudienceArray() throws InvalidJwtException, MalformedClaimException
{
    JwtClaims claims = JwtClaims.parse("{\"aud\":[]}");
    List<String> audiences = claims.getAudience();
    Assert.assertThat(0, equalTo(audiences.size()));
}
 
Example #15
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleClaimsExampleFromDraft() throws InvalidJwtException, MalformedClaimException
{
    // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-3.1
    String json = "     {\"iss\":\"joe\",\n" +
            "      \"exp\":1300819380,\n" +
            "      \"http://example.com/is_root\":true}";

    JwtClaims jcs = JwtClaims.parse(json);
    Assert.assertThat("joe", equalTo(jcs.getIssuer()));
    Assert.assertThat(NumericDate.fromSeconds(1300819380), equalTo(jcs.getExpirationTime()));
    Assert.assertTrue(jcs.getClaimValue("http://example.com/is_root", Boolean.class));
}
 
Example #16
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAudienceSingleValue() throws InvalidJwtException, MalformedClaimException
{
    JwtClaims claims = JwtClaims.parse("{\"aud\":\"one\"}");
    List<String> audiences = claims.getAudience();
    Assert.assertThat(1, equalTo(audiences.size()));
    Assert.assertThat("one", equalTo(audiences.get(0)));
}
 
Example #17
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubject() throws InvalidJwtException, MalformedClaimException
{
    String sub = "[email protected]";
    JwtClaims claims = JwtClaims.parse("{\"sub\":\"" + sub + "\"}");
    Assert.assertThat(sub, equalTo(claims.getSubject()));
}
 
Example #18
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetJti() throws InvalidJwtException, MalformedClaimException
{
    String jti = "Xk9c2inNN8fFs60epZil3";
    JwtClaims claims = JwtClaims.parse("{\"jti\":\"" + jti + "\"}");
    Assert.assertThat(jti, equalTo(claims.getJwtId()));
}
 
Example #19
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGettingHelpers() throws InvalidJwtException, MalformedClaimException
{
    String stringClaimName = "string";
    String stringClaimValue = "a value";
    String stringArrayClaimName = "array";
    String json = "{\""+stringClaimName+"\":\""+stringClaimValue+"\", \""+stringArrayClaimName+"\":[\"one\", \"two\", \"three\"]}";
    JwtClaims claims = JwtClaims.parse(json);
    Assert.assertTrue(claims.isClaimValueOfType(stringClaimName, String.class));
    Assert.assertTrue(claims.isClaimValueString(stringClaimName));
    Assert.assertFalse(claims.isClaimValueStringList(stringClaimName));
    Assert.assertFalse(claims.isClaimValueOfType(stringClaimName, Number.class));
    Assert.assertFalse(claims.isClaimValueOfType(stringClaimName, Long.class));
    Assert.assertFalse(claims.isClaimValueOfType(stringClaimName, List.class));
    Assert.assertFalse(claims.isClaimValueOfType(stringClaimName, Boolean.class));

    Assert.assertTrue(claims.isClaimValueStringList(stringArrayClaimName));
    Assert.assertTrue(claims.isClaimValueOfType(stringArrayClaimName, List.class));
    Assert.assertFalse(claims.isClaimValueString(stringArrayClaimName));
    Assert.assertFalse(claims.isClaimValueOfType(stringArrayClaimName, String.class));
    Assert.assertFalse(claims.isClaimValueOfType(stringArrayClaimName, Number.class));
    Assert.assertFalse(claims.isClaimValueOfType(stringArrayClaimName, Long.class));
    Assert.assertTrue(claims.isClaimValueOfType(stringArrayClaimName, List.class));
    Assert.assertFalse(claims.isClaimValueOfType(stringArrayClaimName, Boolean.class));

    String nonexistentClaimName= "nope";
    Assert.assertFalse(claims.isClaimValueOfType(nonexistentClaimName, String.class));
    Assert.assertFalse(claims.isClaimValueOfType(nonexistentClaimName, List.class));
    Assert.assertFalse(claims.isClaimValueOfType(nonexistentClaimName, Boolean.class));
    Assert.assertFalse(claims.isClaimValueOfType(nonexistentClaimName, Number.class));

    Assert.assertFalse(claims.isClaimValueString(nonexistentClaimName));
    Assert.assertFalse(claims.isClaimValueStringList(nonexistentClaimName));

    Assert.assertThat(stringClaimValue, equalTo(claims.getStringClaimValue(stringClaimName)));
    Assert.assertNull(claims.getStringClaimValue(nonexistentClaimName));
    Assert.assertNull(claims.getStringListClaimValue(nonexistentClaimName));
}
 
Example #20
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetExp() throws InvalidJwtException, MalformedClaimException
{
    long exp = 1418823169;
    JwtClaims claims = JwtClaims.parse("{\"exp\":" + exp + "}");
    Assert.assertThat(exp, equalTo(claims.getExpirationTime().getValue()));
}
 
Example #21
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAudienceMultipleInArray() throws InvalidJwtException, MalformedClaimException
{
    JwtClaims claims = JwtClaims.parse("{\"aud\":[\"one\",\"two\",\"three\"]}");
    List<String> audiences = claims.getAudience();
    Assert.assertThat(3, equalTo(audiences.size()));
    Iterator<String> iterator = audiences.iterator();
    Assert.assertThat("one", equalTo(iterator.next()));
    Assert.assertThat("two", equalTo(iterator.next()));
    Assert.assertThat("three", equalTo(iterator.next()));
}
 
Example #22
Source File: JwtClaimsTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetIssuer() throws InvalidJwtException, MalformedClaimException
{
    String issuer = "https//idp.example.com";
    JwtClaims claims = JwtClaims.parse("{\"iss\":\"" + issuer + "\"}");
    Assert.assertThat(issuer, equalTo(claims.getIssuer()));
}
 
Example #23
Source File: JwtClaims.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
private JwtClaims(String jsonClaims) throws InvalidJwtException
{
    rawJson = jsonClaims;
    try
    {
        Map<String, Object> parsed = JsonUtil.parseJson(jsonClaims);
        claimsMap = new LinkedHashMap<>(parsed);
    }
    catch (JoseException e)
    {
        throw new InvalidJwtException("Unable to parse JWT Claim Set JSON: " + jsonClaims, e);
    }
}
 
Example #24
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public static JWTokenUserGroupMapping validateAuthToken(Key key, String jwt) {

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setVerificationKey(key)
                .setRelaxVerificationKeyValidation()
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
            String subject = jwtClaims.getSubject();

            try (JsonReader reader = Json.createReader(new StringReader(subject))) {
                JsonObject subjectObject = reader.readObject(); // JsonParsingException
                String login = subjectObject.getString(SUBJECT_LOGIN); // Npe
                String groupName = subjectObject.getString(SUBJECT_GROUP_NAME); // Npe

                if (login != null && !login.isEmpty() && groupName != null && !groupName.isEmpty()) {
                    return new JWTokenUserGroupMapping(jwtClaims, new UserGroupMapping(login, groupName));
                }
            }


        } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
            LOGGER.log(Level.FINE, "Cannot validate jwt token", e);
        }

        return null;

    }
 
Example #25
Source File: GrantByClientCredentialTest.java    From demo-spring-boot-security-oauth2 with MIT License 5 votes vote down vote up
@Test
public void accessProtectedResourceByJwtToken() throws JsonParseException, JsonMappingException, IOException, InvalidJwtException {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/client", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    JwtContext jwtContext = jwtConsumer.process(accessToken);
    logJWTClaims(jwtContext);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("trusted-app", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/trusted_client", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_TRUSTED_CLIENT\"}]", response.getBody());

}
 
Example #26
Source File: AbstractVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = {BadJWTException.class, InvalidJwtException.class, TokenExpiredException.class, ExpiredJwtException.class},
    description = "Illustrate validation of exp")
public void testFailExpired() throws Exception {
    HashMap<String, Long> timeClaims = new HashMap<>();
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.EXP);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields, timeClaims);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    int expGracePeriodSecs = 60;
    validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
 
Example #27
Source File: AbstractVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = {JOSEException.class, AlgorithmMismatchException.class, InvalidJwtException.class, UnsupportedJwtException.class},
    description = "Illustrate validation of signature algorithm")
public void testFailSignatureAlgorithm() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.ALG);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    int expGracePeriodSecs = 60;
    validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
 
Example #28
Source File: AbstractVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = {BadJWTException.class, InvalidJwtException.class, InvalidClaimException.class, IncorrectClaimException.class},
    description = "Illustrate validation of issuer")
public void testBadIssuer() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.ISSUER);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    int expGracePeriodSecs = 60;
    validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
 
Example #29
Source File: AbstractJWKSTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure a token is validated by the provider using the JWKS URL for the public key associated
 * with the signer.
 *
 * @throws Exception
 */
@Test(expectedExceptions = {InvalidJwtException.class, BadJOSEException.class, JWTVerificationException.class})
public void testNoMatchingKID() throws Exception {
    PrivateKey pk = loadPrivateKey();
    String token = TokenUtils.generateTokenString(pk, "invalid-kid", "/Token1.json", null, null);
    int expGracePeriodSecs = 60;
    validateToken(token, new URL(endpoint), TEST_ISSUER, expGracePeriodSecs);
}
 
Example #30
Source File: TokenUtilsSignEncryptTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
        description = "Illustrate validation failure if signed token is encrypted and no 'cty' header is set")
public void testEncryptSignedClaimsWithoutCty() throws Exception {
    PrivateKey signingKey = TokenUtils.readPrivateKey("/privateKey.pem");
    PublicKey encryptionKey = TokenUtils.readPublicKey("/publicKey.pem");
    String token =
        TokenUtils.signEncryptClaims(signingKey, "1", encryptionKey, "2", "/Token1.json", false);
    validateToken(token, true);
}