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

The following examples show how to use org.jose4j.jwt.JwtClaims#getClaimValue() . 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: DefaultJWTTokenParser.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private void mapRoles(JwtClaims claimsSet) {
    try {
        @SuppressWarnings("unchecked")
        Map<String, String> rolesMapping = claimsSet.getClaimValue(ROLE_MAPPINGS, Map.class);
        List<String> groups = claimsSet.getStringListClaimValue(Claims.groups.name());
        List<String> allGroups = new ArrayList<>(groups);
        for (Map.Entry<String, String> mapping : rolesMapping.entrySet()) {
            // If the key group is in groups list, add the mapped role
            if (groups.contains(mapping.getKey())) {
                allGroups.add(mapping.getValue());
            }
        }
        // Replace the groups with the original groups + mapped roles
        claimsSet.setStringListClaim(Claims.groups.name(), allGroups);
        PrincipalLogging.log.updatedGroups(allGroups);
    } catch (Exception e) {
        PrincipalLogging.log.failedToAccessRolesMappingClaim(e);
    }
}
 
Example 2
Source File: DefaultJWTTokenParser.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private void checkNameClaims(JwtContext jwtContext) throws InvalidJwtException {
    JwtClaims claimsSet = jwtContext.getJwtClaims();
    final boolean hasPrincipalClaim = claimsSet.getClaimValue(Claims.sub.name()) != null ||
            claimsSet.getClaimValue(Claims.upn.name()) != null ||
            claimsSet.getClaimValue(Claims.preferred_username.name()) != null;

    if (!hasPrincipalClaim) {
        throw PrincipalMessages.msg.claimNotFound(s -> new InvalidJwtException(s, emptyList(), jwtContext));
    }
}
 
Example 3
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 4
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 5
Source File: JWTCredential.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * This just parses the token without validation to extract one of the following in order to obtain
 * the name to be used for the principal:
 * upn
 * preferred_username
 * subject
 *
 * If there is an exception it sets the name to INVALID_TOKEN_NAME and saves the exception for access
 * via {@link #getJwtException()}
 *
 * @return the name to use for the principal
 */
public String getName() {
    if (name == null) {
        name = "INVALID_TOKEN_NAME";
        try {
            // Build a JwtConsumer that doesn't check signatures or do any validation.
            JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder()
                    .setSkipAllValidators()
                    .setDisableRequireSignature()
                    .setSkipSignatureVerification()
                    .build();

            //The first JwtConsumer is basically just used to parse the JWT into a JwtContext object.
            JwtContext jwtContext = firstPassJwtConsumer.process(bearerToken);
            JwtClaims claimsSet = jwtContext.getJwtClaims();
            // We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
            name = claimsSet.getClaimValue("upn", String.class);
            if (name == null) {
                name = claimsSet.getClaimValue("preferred_username", String.class);
                if (name == null) {
                    name = claimsSet.getSubject();
                }
            }
        } catch (Exception e) {
            jwtException = e;
        }
    }
    return name;
}
 
Example 6
Source File: JwtUtil.java    From light with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> verifyJwt(String jwt) throws InvalidJwtException, MalformedClaimException {
    Map<String, Object> user = null;
    X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(certificate);
    x509VerificationKeyResolver.setTryAllOnNoThumbHeader(true);

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime() // the JWT must have an expiration time
            .setAllowedClockSkewInSeconds((Integer) config.get(CLOCK_SKEW_IN_MINUTE)*60) // allow some leeway in validating time based claims to account for clock skew
            .setRequireSubject() // the JWT must have a subject claim
            .setExpectedIssuer(issuer)
            .setExpectedAudience(audience)
            .setVerificationKeyResolver(x509VerificationKeyResolver) // verify the signature with the certificates
            .build(); // create the JwtConsumer instance

    //  Validate the JWT and process it to the Claims
    JwtClaims claims = jwtConsumer.processToClaims(jwt);
    if(claims != null) {
        user = new HashMap<String, Object>();
        user.put("userId", claims.getClaimValue("userId"));
        user.put("clientId", claims.getClaimValue("clientId"));
        List roles = claims.getStringListClaimValue("roles");
        user.put("roles", roles);
        Object host = claims.getClaimValue("host");
        if(host != null) user.put("host", host);
    }
    return user;
}
 
Example 7
Source File: DefaultJWTCallerPrincipal.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
protected static String getRawToken(JwtClaims claimsSet) {
    Object rawToken = claimsSet.getClaimValue(Claims.raw_token.name());
    return rawToken != null ? rawToken.toString() : null;
}
 
Example 8
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void jwt61ExampleUnsecuredJwt() throws InvalidJwtException, MalformedClaimException
{
    // an Example Unsecured JWT from https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-6.1
    String jwt =
            "eyJhbGciOiJub25lIn0" +
            "." +
            "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt" +
            "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ" +
            ".";

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

    JwtContext jwtContext = firstPassConsumer.process(jwt);
    Assert.assertThat("joe", equalTo(jwtContext.getJwtClaims().getIssuer()));
    Assert.assertThat(NumericDate.fromSeconds(1300819380), equalTo(jwtContext.getJwtClaims().getExpirationTime()));
    Assert.assertTrue(jwtContext.getJwtClaims().getClaimValue("http://example.com/is_root", Boolean.class));

    // works w/ 'NO_CONSTRAINTS' and setDisableRequireSignature() and null key
    JwtConsumer consumer = new JwtConsumerBuilder()
            .setVerificationKey(null)
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .setEvaluationTime(NumericDate.fromSeconds(1300819343))
            .setJwsAlgorithmConstraints(AlgorithmConstraints.NO_CONSTRAINTS)
            .setDisableRequireSignature()
            .build();
    JwtClaims jcs = consumer.processToClaims(jwt);
    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));

    consumer.processContext(jwtContext);

    // just ensure that getting claims that aren't there returns null and doesn't throw an exception
    Assert.assertNull(jcs.getStringClaimValue("no-such-claim"));
    Assert.assertNull(jcs.getClaimValue("no way jose", Boolean.class));
    Assert.assertNull(jcs.getStringListClaimValue("nope"));

    Assert.assertTrue(jcs.hasClaim("http://example.com/is_root"));
    Object objectClaimValue = jcs.getClaimValue("http://example.com/is_root");
    Assert.assertNotNull(objectClaimValue);

    Assert.assertFalse(jcs.hasClaim("nope"));
    objectClaimValue = jcs.getClaimValue("nope");
    Assert.assertNull(objectClaimValue);


    // fails w/ default constraints
    consumer = new JwtConsumerBuilder()
            .setVerificationKey(null)
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .setEvaluationTime(NumericDate.fromSeconds(1300819343))
            .build();
     SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, consumer);

    // fails w/ explicit constraints
    consumer = new JwtConsumerBuilder()
            .setVerificationKey(null)
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .setEvaluationTime(NumericDate.fromSeconds(1300819343))
            .setJwsAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.BLACKLIST, AlgorithmIdentifiers.NONE, AlgorithmIdentifiers.RSA_PSS_USING_SHA256))
            .build();
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, consumer);


    // fail w/ 'NO_CONSTRAINTS' but a key provided
    consumer = new JwtConsumerBuilder()
            .setVerificationKey(ExampleRsaJwksFromJwe.APPENDIX_A_1.getKey())
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .setEvaluationTime(NumericDate.fromSeconds(1300819343))
            .setJwsAlgorithmConstraints(AlgorithmConstraints.NO_CONSTRAINTS)
            .build();
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, consumer);

    // fail w/ 'NO_CONSTRAINTS' and no key but sig required (by default)
    consumer = new JwtConsumerBuilder()
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .setEvaluationTime(NumericDate.fromSeconds(1300819343))
            .setJwsAlgorithmConstraints(AlgorithmConstraints.NO_CONSTRAINTS)
            .build();
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, consumer);
}