Search in sources :

Example 1 with OIDCException

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

the class JWTHelper method decryptJWE.

public String decryptJWE(String jwe, JWKSet jwkSet) throws OIDCException {
    JWEObject jweObject;
    try {
        jweObject = JWEObject.parse(jwe);
    } catch (ParseException e) {
        throw new JWTException.Parse(e);
    }
    if (logger.isTraceEnabled()) {
        logger.trace("jwe.header=" + jweObject.getHeader().toString());
    }
    JWEAlgorithm alg = jweObject.getHeader().getAlgorithm();
    EncryptionMethod enc = jweObject.getHeader().getEncryptionMethod();
    String kid = jweObject.getHeader().getKeyID();
    if (alg == null) {
        alg = JWEAlgorithm.parse(options.getDefaultJWEAlgorithm());
    }
    if (enc == null) {
        enc = EncryptionMethod.parse(options.getDefaultJWEEncryption());
    }
    if (!isValidAlgorithm(alg)) {
        throw new JWTException.UnsupportedAlgorithm(alg.toString());
    }
    try {
        JWK jwk = jwkSet.getKeyByKeyId(kid);
        if (jwk == null) {
            throw new JWTException.UnknownKid(kid, jwkSet.toString());
        }
        JWEDecrypter decrypter = getJWEDecrypter(alg, enc, jwk);
        jweObject.decrypt(decrypter);
    } catch (Exception e) {
        throw new JWTException.Decryption(e);
    }
    String jws = jweObject.getPayload().toString();
    if (logger.isDebugEnabled()) {
        logger.debug("Decrypted JWE as: " + jws);
    }
    // TODO: remove
    logger.info("KK Decrypted JWE as: " + jws);
    return jws;
}
Also used : JWTException(it.spid.cie.oidc.exception.JWTException) EncryptionMethod(com.nimbusds.jose.EncryptionMethod) JOSEException(com.nimbusds.jose.JOSEException) JWTException(it.spid.cie.oidc.exception.JWTException) OIDCException(it.spid.cie.oidc.exception.OIDCException) ParseException(java.text.ParseException) JWEDecrypter(com.nimbusds.jose.JWEDecrypter) JWEObject(com.nimbusds.jose.JWEObject) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) ParseException(java.text.ParseException) JWK(com.nimbusds.jose.jwk.JWK)

Example 2 with OIDCException

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

the class JWTHelper method createJWS.

public String createJWS(JSONObject payload, JWKSet jwks) throws OIDCException {
    JWK jwk = getFirstJWK(jwks);
    // Signer depends on JWK key type
    JWSAlgorithm alg;
    JWSSigner signer;
    try {
        if (KeyType.RSA.equals(jwk.getKeyType())) {
            RSAKey rsaKey = (RSAKey) jwk;
            signer = new RSASSASigner(rsaKey);
            alg = JWSAlgorithm.parse(options.getDefaultJWSAlgorithm());
        } else if (KeyType.EC.equals(jwk.getKeyType())) {
            ECKey ecKey = (ECKey) jwk;
            signer = new ECDSASigner(ecKey);
            alg = JWSAlgorithm.parse(options.getDefaultJWSAlgorithm());
        } else {
            throw new JWTException.Generic("Unknown key type");
        }
        // Prepare JWS object with the payload
        JWSObject jwsObject = new JWSObject(new JWSHeader.Builder(alg).keyID(jwk.getKeyID()).build(), new Payload(payload.toString()));
        // Compute the signature
        jwsObject.sign(signer);
        // Serialize to compact form
        return jwsObject.serialize();
    } catch (Exception e) {
        throw new JWTException.Generic(e);
    }
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) JWTException(it.spid.cie.oidc.exception.JWTException) ECKey(com.nimbusds.jose.jwk.ECKey) 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) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) Payload(com.nimbusds.jose.Payload) JWSObject(com.nimbusds.jose.JWSObject) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 3 with OIDCException

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

the class OAuth2Helper method performAccessTokenRequest.

/**
 * Obtain the Access Token from the Authorization Code
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.1.3">
 * https://tools.ietf.org/html/rfc6749#section-4.1.3</a>
 *
 * @param redirectUrl
 * @param state
 * @param code
 * @param issuerId
 * @param clientConf
 * @param tokenEndpointUrl
 * @param codeVerifier
 * @return
 * @throws Exception
 */
public JSONObject performAccessTokenRequest(String redirectUrl, String state, String code, String issuerId, FederationEntity clientConf, String tokenEndpointUrl, String codeVerifier) throws OIDCException {
    // create client assertion (JWS Token)
    JSONObject payload = new JSONObject().put("iss", clientConf.getSubject()).put("sub", clientConf.getSubject()).put("aud", JSONUtil.asJSONArray(tokenEndpointUrl)).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("grant_type", "authorization_code");
    params.put("redirect_uri", redirectUrl);
    params.put("client_id", clientConf.getSubject());
    params.put("state", state);
    params.put("code", code);
    params.put("code_verifier", codeVerifier);
    params.put("client_assertion_type", JWT_BARRIER);
    params.put("client_assertion", clientAssertion);
    if (logger.isDebugEnabled()) {
        logger.debug("Access Token Request for {}: {}", state, buildPostBody(params));
    }
    try {
        HttpRequest request = HttpRequest.newBuilder().uri(new URI(tokenEndpointUrl)).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("Something went wrong with {}: {}", state, response.statusCode());
        } else {
            try {
                return new JSONObject(response.body());
            } catch (Exception e) {
                logger.error("Something went wrong with {}: {}", state, e.getMessage());
            }
        }
        return new JSONObject();
    } 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 4 with OIDCException

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

the class EntityConfiguration method validateBySuperior.

/**
 * Validate this EntityConfiguration with the jwks contained in the statement of the
 * superior
 *
 * @param jwt the statement issued by the superior
 * @param ec the superior entity configuration
 * @return
 * @throws OIDCException
 */
public boolean validateBySuperior(String jwt, EntityConfiguration ec) throws OIDCException {
    boolean valid = false;
    JSONObject payload = null;
    try {
        payload = JWTHelper.fastParsePayload(jwt);
        if (ec.validateItself(false)) {
            if (ec.validateDescendant(jwt)) {
                // Validate entity JWS using superior JWKSet
                JWKSet jwkSet = JWTHelper.getJWKSetFromJWT(jwt);
                valid = jwtHelper.verifyJWS(this.jwt, jwkSet);
            }
        }
    } catch (Exception e) {
        StringBuilder sb = new StringBuilder();
        sb.append(getSubject());
        sb.append(" failed validation with ");
        sb.append(ec.getSubject());
        sb.append("'s superior statement ");
        if (payload != null) {
            sb.append(payload.toString());
        } else {
            sb.append(jwt);
        }
        sb.append(". Exception ");
        sb.append(e);
        logger.warn(sb.toString());
    }
    if (valid) {
        ec.addVerifiedDescendantStatement(getSubject(), payload);
        this.verifiedBySuperiors.put(payload.getString("iss"), ec);
        this.valid = true;
    } else {
        ec.addFailedDescendantStatement(getSubject(), payload);
    }
    return valid;
}
Also used : JSONObject(org.json.JSONObject) JWKSet(com.nimbusds.jose.jwk.JWKSet) 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)

Example 5 with OIDCException

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

the class RelyingPartyHandler method getWellKnownData.

/**
 * Return the "Well Known" information of the current Relying Party. The completeness
 * of these informations depends of the federation on-boarding status of the entity.
 *
 * @param requestURL
 * @param jsonMode
 * @return
 * @throws OIDCException
 */
public WellKnownData getWellKnownData(String requestURL, boolean jsonMode) throws OIDCException {
    String sub = getSubjectFromURL(requestURL);
    if (!Objects.equals(sub, options.getClientId())) {
        throw new OIDCException(String.format("Sub doesn't match %s : %s", sub, options.getClientId()));
    }
    FederationEntity conf = persistence.fetchFederationEntity(sub, true);
    if (conf == null) {
        return prepareOnboardingData(sub, jsonMode);
    } else {
        return getWellKnownData(conf, jsonMode);
    }
}
Also used : FederationEntity(it.spid.cie.oidc.model.FederationEntity) OIDCException(it.spid.cie.oidc.exception.OIDCException)

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