use of com.nimbusds.jwt.EncryptedJWT in project identity-test-integration by wso2-incubator.
the class IDTokenDecrypterServlet method doPost.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String idToken = request.getParameter("idToken");
String privateKeyString = request.getParameter("privateKeyString");
ServletOutputStream out = response.getOutputStream();
if (StringUtils.isBlank(privateKeyString)) {
response.setStatus(HttpStatus.SC_BAD_REQUEST);
out.print("Client private key cannot be empty!");
} else if (StringUtils.isBlank(idToken)) {
response.setStatus(HttpStatus.SC_BAD_REQUEST);
out.print("Error occurred while decrypting: Empty id token received!");
} else {
response.setContentType("application/json");
EncryptedJWT encryptedJWT;
try {
encryptedJWT = decryptJWE(idToken, privateKeyString);
JSONObject outJSON = new JSONObject();
JSONObject claimsJSON = new JSONObject();
// Get all claims set to a map and return a JSON object.
Map<String, Object> allClaims = encryptedJWT.getJWTClaimsSet().getAllClaims();
for (Map.Entry<String, Object> entry : allClaims.entrySet()) {
claimsJSON.put(entry.getKey(), entry.getValue());
}
outJSON.put("claims", claimsJSON);
// Get JWT header data.
outJSON.put("header", encryptedJWT.getHeader().toJSONObject());
out.print(outJSON.toString());
} catch (NoSuchAlgorithmException | ParseException | JOSEException | IllegalArgumentException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
response.setStatus(HttpStatus.SC_BAD_REQUEST);
out.print("Error occurred while decrypting id token.");
} catch (InvalidKeySpecException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
response.setStatus(HttpStatus.SC_BAD_REQUEST);
out.print("Invalid client private key.");
}
}
}
use of com.nimbusds.jwt.EncryptedJWT in project identity-test-integration by wso2-incubator.
the class IDTokenDecrypterServlet method decryptJWE.
/**
* Decrypt the id token using the private key.
*
* @param JWE id token to be decrypted
* @param privateKeyString client private key as a string
* @return decrypted id token as an EncryptedJWT object
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws ParseException
* @throws JOSEException
* @throws IllegalArgumentException
*/
private EncryptedJWT decryptJWE(String JWE, String privateKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException, ParseException, JOSEException, IllegalArgumentException {
KeyFactory kf = KeyFactory.getInstance("RSA");
// Remove EOF characters from key string and generate key object.
privateKeyString = privateKeyString.replace("\n", "").replace("\r", "");
PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
PrivateKey privateKey = kf.generatePrivate(keySpecPKCS8);
EncryptedJWT jwt = EncryptedJWT.parse(JWE);
// Create a decrypter with the specified private RSA key.
RSADecrypter decrypter = new RSADecrypter((RSAPrivateKey) privateKey);
jwt.decrypt(decrypter);
return jwt;
}
use of com.nimbusds.jwt.EncryptedJWT in project pac4j by pac4j.
the class JwtAuthenticator method validate.
@Override
public void validate(final TokenCredentials credentials, final WebContext context) {
init();
final String token = credentials.getToken();
if (context != null) {
// set the www-authenticate in case of error
context.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Bearer realm=\"" + realmName + "\"");
}
try {
// Parse the token
JWT jwt = JWTParser.parse(token);
if (jwt instanceof PlainJWT) {
if (signatureConfigurations.isEmpty()) {
logger.debug("JWT is not signed and no signature configurations -> verified");
} else {
throw new CredentialsException("A non-signed JWT cannot be accepted as signature configurations have been defined");
}
} else {
SignedJWT signedJWT = null;
if (jwt instanceof SignedJWT) {
signedJWT = (SignedJWT) jwt;
}
// encrypted?
if (jwt instanceof EncryptedJWT) {
logger.debug("JWT is encrypted");
final EncryptedJWT encryptedJWT = (EncryptedJWT) jwt;
boolean found = false;
final JWEHeader header = encryptedJWT.getHeader();
final JWEAlgorithm algorithm = header.getAlgorithm();
final EncryptionMethod method = header.getEncryptionMethod();
for (final EncryptionConfiguration config : encryptionConfigurations) {
if (config.supports(algorithm, method)) {
logger.debug("Using encryption configuration: {}", config);
try {
config.decrypt(encryptedJWT);
signedJWT = encryptedJWT.getPayload().toSignedJWT();
if (signedJWT != null) {
jwt = signedJWT;
}
found = true;
break;
} catch (final JOSEException e) {
logger.debug("Decryption fails with encryption configuration: {}, passing to the next one", config);
}
}
}
if (!found) {
throw new CredentialsException("No encryption algorithm found for JWT: " + token);
}
}
// signed?
if (signedJWT != null) {
logger.debug("JWT is signed");
boolean verified = false;
boolean found = false;
final JWSAlgorithm algorithm = signedJWT.getHeader().getAlgorithm();
for (final SignatureConfiguration config : signatureConfigurations) {
if (config.supports(algorithm)) {
logger.debug("Using signature configuration: {}", config);
try {
verified = config.verify(signedJWT);
found = true;
if (verified) {
break;
}
} catch (final JOSEException e) {
logger.debug("Verification fails with signature configuration: {}, passing to the next one", config);
}
}
}
if (!found) {
throw new CredentialsException("No signature algorithm found for JWT: " + token);
}
if (!verified) {
throw new CredentialsException("JWT verification failed: " + token);
}
}
}
createJwtProfile(credentials, jwt);
} catch (final ParseException e) {
throw new CredentialsException("Cannot decrypt / verify JWT", e);
}
}
use of com.nimbusds.jwt.EncryptedJWT in project pac4j by pac4j.
the class AbstractEncryptionConfiguration method encrypt.
@Override
public String encrypt(final JWT jwt) {
init();
if (jwt instanceof SignedJWT) {
// Create JWE object with signed JWT as payload
final JWEObject jweObject = new JWEObject(new JWEHeader.Builder(this.algorithm, this.method).contentType("JWT").build(), new Payload((SignedJWT) jwt));
try {
// Perform encryption
jweObject.encrypt(buildEncrypter());
} catch (final JOSEException e) {
throw new TechnicalException(e);
}
// Serialise to JWE compact form
return jweObject.serialize();
} else {
// create header
final JWEHeader header = new JWEHeader(this.algorithm, this.method);
try {
// encrypted jwt
EncryptedJWT encryptedJwt = new EncryptedJWT(header, jwt.getJWTClaimsSet());
// Perform encryption
encryptedJwt.encrypt(buildEncrypter());
// serialize
return encryptedJwt.serialize();
} catch (final JOSEException | ParseException e) {
throw new TechnicalException(e);
}
}
}
Aggregations