Search in sources :

Example 11 with OIDCException

use of it.spid.cie.oidc.exception.OIDCException in project spid-cie-oidc-java by italia.

the class JWTHelper method verifyJWS.

public boolean verifyJWS(SignedJWT jws, JWKSet jwkSet) throws OIDCException {
    String kid = jws.getHeader().getKeyID();
    JWK jwk = jwkSet.getKeyByKeyId(kid);
    if (jwk == null) {
        throw new JWTException.UnknownKid(kid, jwkSet.toString());
    }
    JWSAlgorithm alg = jws.getHeader().getAlgorithm();
    if (!isValidAlgorithm(alg)) {
        throw new JWTException.UnsupportedAlgorithm(alg.toString());
    }
    try {
        JWSVerifier verifier = getJWSVerifier(alg, jwk);
        return jws.verify(verifier);
    } catch (Exception e) {
        throw new JWTException.Verifier(e);
    }
}
Also used : JWTException(it.spid.cie.oidc.exception.JWTException) JWSVerifier(com.nimbusds.jose.JWSVerifier) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JOSEException(com.nimbusds.jose.JOSEException) JWTException(it.spid.cie.oidc.exception.JWTException) OIDCException(it.spid.cie.oidc.exception.OIDCException) ParseException(java.text.ParseException) JWK(com.nimbusds.jose.jwk.JWK)

Example 12 with OIDCException

use of it.spid.cie.oidc.exception.OIDCException in project spid-cie-oidc-java by italia.

the class OAuth2Helper method sendRevocationRequest.

public void sendRevocationRequest(String token, String clientId, String revocationUrl, FederationEntity clientConf) throws OIDCException {
    // create client assertion (JWS Token)
    JSONObject payload = new JSONObject().put("iss", clientId).put("sub", clientId).put("aud", JSONUtil.asJSONArray(revocationUrl)).put("iat", JWTHelper.getIssuedAt()).put("exp", JWTHelper.getExpiresOn()).put("jti", UUID.randomUUID().toString());
    JWKSet jwkSet = JWTHelper.getJWKSetFromJSON(clientConf.getJwks());
    String clientAssertion = jwtHelper.createJWS(payload, jwkSet);
    // Body Parameters
    Map<String, Object> params = new HashMap<>();
    params.put("token", token);
    params.put("client_id", clientId);
    params.put("client_assertion", clientAssertion);
    params.put("client_assertion_type", JWT_BARRIER);
    if (logger.isDebugEnabled()) {
        logger.debug("Send Token Revocation: {}", buildPostBody(params));
    }
    try {
        HttpRequest request = HttpRequest.newBuilder().uri(new URI(revocationUrl)).POST(HttpRequest.BodyPublishers.ofString(buildPostBody(params))).header("Content-Type", "application/x-www-form-urlencoded").build();
        // TODO timeout from options
        HttpResponse<String> response = HttpClient.newBuilder().build().send(request, BodyHandlers.ofString());
        if (response.statusCode() != 200) {
            logger.error("Token revocation failed: {}", response.statusCode());
        }
    } catch (Exception e) {
        throw new OIDCException(e);
    }
}
Also used : HttpRequest(java.net.http.HttpRequest) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) JWKSet(com.nimbusds.jose.jwk.JWKSet) OIDCException(it.spid.cie.oidc.exception.OIDCException) JSONObject(org.json.JSONObject) URI(java.net.URI) OIDCException(it.spid.cie.oidc.exception.OIDCException)

Example 13 with OIDCException

use of it.spid.cie.oidc.exception.OIDCException in project spid-cie-oidc-java by italia.

the class OIDCHelper method getUserInfo.

public JSONObject getUserInfo(String state, String accessToken, JSONObject providerConf, boolean verify, JWKSet entityJwks) throws OIDCException {
    try {
        HttpRequest request = HttpRequest.newBuilder().uri(new URI(providerConf.optString("userinfo_endpoint"))).header("Authorization", "Bearer " + accessToken).GET().build();
        HttpResponse<String> response = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build().send(request, BodyHandlers.ofString());
        if (response.statusCode() != 200) {
            String msg = String.format("Something went wrong with %s: %d", state, response.statusCode());
            throw new OIDCException(msg);
        }
        JWKSet providerJwks = JWTHelper.getJWKSetFromJSON(providerConf.optJSONObject("jwks"));
        JSONObject jwt = jwtHelper.getJWTFromJWE(response.body(), entityJwks, providerJwks);
        // TODO: Debug
        logger.info("Userinfo endpoint result: " + jwt.toString(2));
        return jwt.getJSONObject("payload");
    } catch (OIDCException e) {
        throw e;
    } catch (Exception e) {
        throw new OIDCException(e);
    }
}
Also used : HttpRequest(java.net.http.HttpRequest) JSONObject(org.json.JSONObject) OIDCException(it.spid.cie.oidc.exception.OIDCException) JWKSet(com.nimbusds.jose.jwk.JWKSet) URI(java.net.URI) OIDCException(it.spid.cie.oidc.exception.OIDCException)

Example 14 with OIDCException

use of it.spid.cie.oidc.exception.OIDCException in project spid-cie-oidc-java by italia.

the class EntityConfiguration method validateByAllowedTrustMarks.

/**
 * Validate the entity configuration only if marked by a well known trust mark, issued
 * by a trusted issuer
 *
 * @return
 * @throws OIDCException
 */
public boolean validateByAllowedTrustMarks() throws OIDCException {
    if (trustAnchor == null) {
        throw new TrustChainException.TrustAnchorNeeded("To validate the trust marks the Trust Anchor Entity Configuration " + "is needed.");
    }
    if (allowedTrustMarks.isEmpty()) {
        return true;
    }
    JSONArray jsonTrustMarks = payload.optJSONArray("trust_marks");
    if (jsonTrustMarks == null) {
        logger.warn("{} doesn't have the trust marks claim in its Entity Configuration", this.sub);
        return false;
    }
    List<TrustMark> trustMarks = new ArrayList<>();
    for (int x = 0; x < jsonTrustMarks.length(); x++) {
        JSONObject jsonTrustMark = jsonTrustMarks.optJSONObject(x);
        if (jsonTrustMark == null) {
            logger.warn("invalid trust_mark at " + x + " on " + trustMarks.toString());
            continue;
        } else if (!isTrustMarkAllowed(jsonTrustMark)) {
            continue;
        }
        try {
            trustMarks.add(new TrustMark(jsonTrustMark.optString("trust_mark"), jwtHelper));
        } catch (Exception e) {
            logger.error("Trust Mark decoding failed on {}", jsonTrustMark);
        }
    }
    if (trustMarks.isEmpty()) {
        throw new EntityException.MissingTrustMarks("Required Trust marks are missing.");
    }
    Map<String, Set<String>> trustAnchorIssuers = trustAnchor.getTrustMarksIssuers();
    boolean valid = false;
    for (TrustMark trustMark : trustMarks) {
        Set<String> issuers = trustAnchorIssuers.get(trustMark.getId());
        if (issuers != null) {
            if (!issuers.contains(trustMark.getIssuer())) {
                valid = false;
            } else {
                valid = trustMark.validateByIssuer();
            }
        } else {
            valid = trustMark.validate(trustAnchor);
        }
        if (!trustMark.isValid()) {
            valid = false;
        }
        if (valid) {
            if (logger.isInfoEnabled()) {
                logger.info("Trust Mark {} is valid", trustMark);
            }
            this.verifiedTrustMarks.add(trustMark);
        } else if (logger.isWarnEnabled()) {
            logger.warn("Trust Mark {} is not valid", trustMark);
        }
    }
    return valid;
}
Also used : JWKSet(com.nimbusds.jose.jwk.JWKSet) HashSet(java.util.HashSet) Set(java.util.Set) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JWTException(it.spid.cie.oidc.exception.JWTException) OIDCException(it.spid.cie.oidc.exception.OIDCException) TrustChainException(it.spid.cie.oidc.exception.TrustChainException) EntityException(it.spid.cie.oidc.exception.EntityException) JSONObject(org.json.JSONObject)

Example 15 with OIDCException

use of it.spid.cie.oidc.exception.OIDCException in project spid-cie-oidc-java by italia.

the class TrustChainBuilder method processSubjectConfiguration.

/**
 * Ensure the provided Subject Entity Configuration is valid (self validable) and
 * complete (at least by required elements)
 *
 * @throws OIDCException
 *
 * @throws OIDCException
 */
protected void processSubjectConfiguration() throws OIDCException {
    if (subjectConfiguration != null) {
        return;
    }
    try {
        String jwt = EntityHelper.getEntityConfiguration(subject);
        subjectConfiguration = new EntityConfiguration(jwt, trustAnchorConfiguration, jwtHelper);
        subjectConfiguration.validateItself();
    } catch (Exception e) {
        String msg = String.format("Entity Configuration for %s failed: %s", subject, e.getMessage());
        logger.error(msg);
        throw new TrustChainBuilderException(msg);
    }
    if (requiredTrustMasks.length > 0) {
        subjectConfiguration.setAllowedTrustMarks(requiredTrustMasks);
        if (!subjectConfiguration.validateByAllowedTrustMarks()) {
            throw new TrustChainException.InvalidRequiredTrustMark("The required Trust Marks are not valid");
        }
        this.verifiedTrustMasks.addAll(subjectConfiguration.getVerifiedTrustMarks());
    }
}
Also used : TrustChainBuilderException(it.spid.cie.oidc.exception.TrustChainBuilderException) OIDCException(it.spid.cie.oidc.exception.OIDCException) TrustChainException(it.spid.cie.oidc.exception.TrustChainException) TrustChainBuilderException(it.spid.cie.oidc.exception.TrustChainBuilderException)

Aggregations

OIDCException (it.spid.cie.oidc.exception.OIDCException)16 JSONObject (org.json.JSONObject)9 JWKSet (com.nimbusds.jose.jwk.JWKSet)7 JWTException (it.spid.cie.oidc.exception.JWTException)7 TrustChainException (it.spid.cie.oidc.exception.TrustChainException)6 JOSEException (com.nimbusds.jose.JOSEException)5 ParseException (java.text.ParseException)5 URI (java.net.URI)4 HttpRequest (java.net.http.HttpRequest)4 JWK (com.nimbusds.jose.jwk.JWK)3 EntityException (it.spid.cie.oidc.exception.EntityException)3 FederationEntity (it.spid.cie.oidc.model.FederationEntity)3 JSONArray (org.json.JSONArray)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)2 RelyingPartyException (it.spid.cie.oidc.exception.RelyingPartyException)2 SchemaException (it.spid.cie.oidc.exception.SchemaException)2 TrustChainBuilderException (it.spid.cie.oidc.exception.TrustChainBuilderException)2 AuthnRequest (it.spid.cie.oidc.model.AuthnRequest)2 HashMap (java.util.HashMap)2 EncryptionMethod (com.nimbusds.jose.EncryptionMethod)1