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;
}
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);
}
}
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);
}
}
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;
}
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);
}
}
Aggregations