Java Code Examples for org.apache.cxf.rs.security.jose.jwt.JwtClaims#getClaim()

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtClaims#getClaim() . 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: AbstractHTTPJwtAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
protected String extractSubject(JwtClaims claims) {
    String subject = claims.getSubject();

    if (subjectKey != null) {
        Object subjectObject = claims.getClaim(subjectKey);

        if (subjectObject == null) {
            log.warn("Failed to get subject from JWT claims, check if subject_key '{}' is correct.", subjectKey);
            return null;
        }

        // We expect a String. If we find something else, convert to String but issue a
        // warning
        if (!(subjectObject instanceof String)) {
            log.warn(
                    "Expected type String for roles in the JWT for subject_key {}, but value was '{}' ({}). Will convert this value to String.",
                    subjectKey, subjectObject, subjectObject.getClass());
            subject = String.valueOf(subjectObject);
        } else {
            subject = (String) subjectObject;
        }
    }
    return subject;
}
 
Example 2
Source File: AbstractHTTPJwtAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected String[] extractRoles(JwtClaims claims) {
    if (rolesKey == null) {
        return new String[0];
    }

    Object rolesObject = claims.getClaim(rolesKey);

    if (rolesObject == null) {
        log.warn(
                "Failed to get roles from JWT claims with roles_key '{}'. Check if this key is correct and available in the JWT payload.",
                rolesKey);
        return new String[0];
    }

    String[] roles = String.valueOf(rolesObject).split(",");

    // We expect a String or Collection. If we find something else, convert to
    // String but issue a warning
    if (!(rolesObject instanceof String) && !(rolesObject instanceof Collection<?>)) {
        log.warn(
                "Expected type String or Collection for roles in the JWT for roles_key {}, but value was '{}' ({}). Will convert this value to String.",
                rolesKey, rolesObject, rolesObject.getClass());
    } else if (rolesObject instanceof Collection<?>) {
        roles = ((Collection<String>) rolesObject).toArray(new String[0]);
    }

    for (int i = 0; i < roles.length; i++) {
        roles[i] = roles[i].trim();
    }

    return roles;
}
 
Example 3
Source File: AbstractJwtHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void validateClaims(Client client, JwtClaims claims) {
    if (getAudience() != null) {
        JAXRSUtils.getCurrentMessage().put(JwtConstants.EXPECTED_CLAIM_AUDIENCE, getAudience());
    }
    JwtUtils.validateTokenClaims(claims, ttl, clockOffset, true);

    validateIssuer(claims.getIssuer());
    validateSubject(client, claims.getSubject());

    // We must have an Expiry
    if (claims.getClaim(JwtConstants.CLAIM_EXPIRY) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
}
 
Example 4
Source File: JwtRequestCodeFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public MultivaluedMap<String, String> process(MultivaluedMap<String, String> params,
                                              UserSubject endUser,
                                              Client client) {
    String requestToken = params.getFirst(REQUEST_PARAM);
    if (requestToken == null) {
        String requestUri = params.getFirst(REQUEST_URI_PARAM);
        if (isRequestUriValid(client, requestUri)) {
            requestToken = WebClient.create(requestUri).get(String.class);
        }
    }
    if (requestToken != null) {
        JweDecryptionProvider theDecryptor = super.getInitializedDecryptionProvider(client.getClientSecret());
        JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(client);
        JwtToken jwt = getJwtToken(requestToken, theDecryptor, theSigVerifier);
        JwtClaims claims = jwt.getClaims();

        // Check issuer
        String iss = issuer != null ? issuer : client.getClientId();
        if (!iss.equals(claims.getIssuer())) {
            throw new SecurityException();
        }

        // Check client_id - if present it must match the client_id specified in the request
        if (claims.getClaim(OAuthConstants.CLIENT_ID) != null
            && !claims.getStringProperty(OAuthConstants.CLIENT_ID).equals(client.getClientId())) {
            throw new SecurityException();
        }

        // Check response_type - if present it must match the response_type specified in the request
        String tokenResponseType = (String)claims.getClaim(OAuthConstants.RESPONSE_TYPE);
        if (tokenResponseType != null
            && !tokenResponseType.equals(params.getFirst(OAuthConstants.RESPONSE_TYPE))) {
            throw new SecurityException();
        }

        MultivaluedMap<String, String> newParams = new MetadataMap<>(params);
        Map<String, Object> claimsMap = claims.asMap();
        for (Map.Entry<String, Object> entry : claimsMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map) {
                Map<String, Object> map = CastUtils.cast((Map<?, ?>)value);
                value = jsonHandler.toJson(map);
            } else if (value instanceof List) {
                List<Object> list = CastUtils.cast((List<?>)value);
                value = jsonHandler.toJson(list);
            }
            newParams.putSingle(key, value.toString());
        }
        return newParams;
    }
    return params;
}
 
Example 5
Source File: JwtTokenUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static ServerAccessToken createAccessTokenFromJwt(JoseJwtConsumer consumer,
                                                         String jose,
                                                         ClientRegistrationProvider clientProvider,
                                                         Map<String, String> claimsMap) {
    JwtClaims claims = consumer.getJwtToken(jose).getClaims();

    // 'client_id' or 'cid', default client_id
    String clientIdClaimName =
        JwtTokenUtils.getClaimName(OAuthConstants.CLIENT_ID, OAuthConstants.CLIENT_ID, claimsMap);
    String clientId = claims.getStringProperty(clientIdClaimName);
    Client c = clientProvider.getClient(clientId);

    long issuedAt = claims.getIssuedAt();
    long lifetime = claims.getExpiryTime() - issuedAt;
    BearerAccessToken at = new BearerAccessToken(c, jose, lifetime, issuedAt);

    List<String> audiences = claims.getAudiences();
    if (audiences != null && !audiences.isEmpty()) {
        at.setAudiences(claims.getAudiences());
    }

    String issuer = claims.getIssuer();
    if (issuer != null) {
        at.setIssuer(issuer);
    }
    Object scope = claims.getClaim(OAuthConstants.SCOPE);
    if (scope != null) {
        String[] scopes = scope instanceof String
            ? scope.toString().split(" ") : CastUtils.cast((List<?>)scope).toArray(new String[]{});
        List<OAuthPermission> perms = new LinkedList<>();
        for (String s : scopes) {
            if (!StringUtils.isEmpty(s)) {
                perms.add(new OAuthPermission(s.trim()));
            }
        }
        at.setScopes(perms);
    }
    final String usernameProp = "username";
    String usernameClaimName =
        JwtTokenUtils.getClaimName(usernameProp, usernameProp, claimsMap);
    String username = claims.getStringProperty(usernameClaimName);
    String subject = claims.getSubject();
    if (username != null) {
        UserSubject userSubject = new UserSubject(username);
        if (subject != null) {
            userSubject.setId(subject);
        }
        at.setSubject(userSubject);
    } else if (subject != null) {
        at.setSubject(new UserSubject(subject));
    }

    String grantType = claims.getStringProperty(OAuthConstants.GRANT_TYPE);
    if (grantType != null) {
        at.setGrantType(grantType);
    }
    String grantCode = claims.getStringProperty(OAuthConstants.AUTHORIZATION_CODE_GRANT);
    if (grantCode != null) {
        at.setGrantCode(grantCode);
    }
    String codeVerifier = claims.getStringProperty(OAuthConstants.AUTHORIZATION_CODE_VERIFIER);
    if (codeVerifier != null) {
        at.setClientCodeVerifier(codeVerifier);
    }
    String nonce = claims.getStringProperty(OAuthConstants.NONCE);
    if (nonce != null) {
        at.setNonce(nonce);
    }
    
    Map<String, String> extraProperties = CastUtils.cast((Map<?, ?>)claims.getClaim("extra_properties"));
    if (extraProperties != null) {
        at.getExtraProperties().putAll(extraProperties);
        Map<String, Object> cnfClaim = CastUtils.cast((Map<?, ?>)claims.getClaim(JwtConstants.CLAIM_CONFIRMATION));
        if (cnfClaim != null) {
            Object certCnf = cnfClaim.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
            if (certCnf != null) {
                at.getExtraProperties().put(JoseConstants.HEADER_X509_THUMBPRINT_SHA256, certCnf.toString());
            }
        }
    }
    
    return at;
}
 
Example 6
Source File: JwtAccessTokenValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
private AccessTokenValidation convertClaimsToValidation(JwtClaims claims) {
    AccessTokenValidation atv = new AccessTokenValidation();
    atv.setInitialValidationSuccessful(true);
    String clientId = claims.getStringProperty(OAuthConstants.CLIENT_ID);
    if (clientId != null) {
        atv.setClientId(clientId);
    }
    if (claims.getIssuedAt() != null) {
        atv.setTokenIssuedAt(claims.getIssuedAt());
    } else {
        atv.setTokenIssuedAt(OAuthUtils.getIssuedAt());
    }
    if (claims.getExpiryTime() != null) {
        atv.setTokenLifetime(claims.getExpiryTime() - atv.getTokenIssuedAt());
    }
    List<String> audiences = claims.getAudiences();
    if (audiences != null && !audiences.isEmpty()) {
        atv.setAudiences(claims.getAudiences());
    }
    if (claims.getIssuer() != null) {
        atv.setTokenIssuer(claims.getIssuer());
    }
    if (claims.getNotBefore() != null) {
        atv.setTokenNotBefore(claims.getNotBefore());
    }
    Object scope = claims.getClaim(OAuthConstants.SCOPE);
    if (scope != null) {
        String[] scopes = scope instanceof String
            ? scope.toString().split(" ") : CastUtils.cast((List<?>)scope).toArray(new String[]{});
        List<OAuthPermission> perms = new LinkedList<>();
        for (String s : scopes) {
            if (!StringUtils.isEmpty(s)) {
                perms.add(new OAuthPermission(s.trim()));
            }
        }
        atv.setTokenScopes(perms);
    }
    String usernameClaimName =
        JwtTokenUtils.getClaimName(USERNAME_PROP, USERNAME_PROP, jwtAccessTokenClaimMap);
    String username = claims.getStringProperty(usernameClaimName);
    if (username != null) {
        UserSubject userSubject = new UserSubject(username);
        if (claims.getSubject() != null) {
            userSubject.setId(claims.getSubject());
        }
        atv.setTokenSubject(userSubject);
    } else if (claims.getSubject() != null) {
        atv.setTokenSubject(new UserSubject(claims.getSubject()));
    }
    Map<String, String> extraProperties = CastUtils.cast((Map<?, ?>)claims.getClaim("extra_properties"));
    if (extraProperties != null) {
        atv.getExtraProps().putAll(extraProperties);
    }

    Map<String, Object> cnfClaim = CastUtils.cast((Map<?, ?>)claims.getClaim(JwtConstants.CLAIM_CONFIRMATION));
    if (cnfClaim != null) {
        Object certCnf = cnfClaim.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
        if (certCnf != null) {
            atv.getExtraProps().put(JoseConstants.HEADER_X509_THUMBPRINT_SHA256, certCnf.toString());
        }
    }

    return atv;
}