Search in sources :

Example 1 with EncryptedJWT

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.");
        }
    }
}
Also used : JSONObject(net.minidev.json.JSONObject) ServletOutputStream(javax.servlet.ServletOutputStream) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) Map(java.util.Map)

Example 2 with EncryptedJWT

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;
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) KeyFactory(java.security.KeyFactory) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Example 3 with EncryptedJWT

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);
    }
}
Also used : PlainJWT(com.nimbusds.jwt.PlainJWT) SignatureConfiguration(org.pac4j.jwt.config.signature.SignatureConfiguration) EncryptionConfiguration(org.pac4j.jwt.config.encryption.EncryptionConfiguration) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) SignedJWT(com.nimbusds.jwt.SignedJWT) EncryptionMethod(com.nimbusds.jose.EncryptionMethod) CredentialsException(org.pac4j.core.exception.CredentialsException) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWEHeader(com.nimbusds.jose.JWEHeader) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) ParseException(java.text.ParseException) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) JOSEException(com.nimbusds.jose.JOSEException)

Example 4 with EncryptedJWT

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);
        }
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT)

Aggregations

EncryptedJWT (com.nimbusds.jwt.EncryptedJWT)4 SignedJWT (com.nimbusds.jwt.SignedJWT)2 ParseException (java.text.ParseException)2 EncryptionMethod (com.nimbusds.jose.EncryptionMethod)1 JOSEException (com.nimbusds.jose.JOSEException)1 JWEAlgorithm (com.nimbusds.jose.JWEAlgorithm)1 JWEHeader (com.nimbusds.jose.JWEHeader)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 RSADecrypter (com.nimbusds.jose.crypto.RSADecrypter)1 JWT (com.nimbusds.jwt.JWT)1 PlainJWT (com.nimbusds.jwt.PlainJWT)1 KeyFactory (java.security.KeyFactory)1 PrivateKey (java.security.PrivateKey)1 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)1 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)1 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)1 Map (java.util.Map)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 JSONObject (net.minidev.json.JSONObject)1 CredentialsException (org.pac4j.core.exception.CredentialsException)1