Search in sources :

Example 1 with PlainJWT

use of com.nimbusds.jwt.PlainJWT 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 2 with PlainJWT

use of com.nimbusds.jwt.PlainJWT in project spring-security by spring-projects.

the class NimbusJwtDecoder method decode.

/**
 * Decode and validate the JWT from its compact claims representation format
 * @param token the JWT value
 * @return a validated {@link Jwt}
 * @throws JwtException
 */
@Override
public Jwt decode(String token) throws JwtException {
    JWT jwt = parse(token);
    if (jwt instanceof PlainJWT) {
        this.logger.trace("Failed to decode unsigned token");
        throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
    }
    Jwt createdJwt = createJwt(token, jwt);
    return validateJwt(createdJwt);
}
Also used : PlainJWT(com.nimbusds.jwt.PlainJWT) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT)

Example 3 with PlainJWT

use of com.nimbusds.jwt.PlainJWT in project cas by apereo.

the class JWTTokenTicketBuilder method buildJwt.

private String buildJwt(final String jwtId, final String audience, final Date issueDate, final String subject, final Date validUntilDate, final Map<String, Object> attributes) {
    final JWTClaimsSet.Builder claims = new JWTClaimsSet.Builder().audience(audience).issuer(casSeverPrefix).jwtID(jwtId).issueTime(issueDate).subject(subject);
    attributes.forEach(claims::claim);
    claims.expirationTime(validUntilDate);
    final JWTClaimsSet claimsSet = claims.build();
    final JSONObject object = claimsSet.toJSONObject();
    final String jwtJson = object.toJSONString();
    LOGGER.debug("Generated JWT [{}]", JsonValue.readJSON(jwtJson).toString(Stringify.FORMATTED));
    if (tokenCipherExecutor.isEnabled()) {
        return tokenCipherExecutor.encode(jwtJson);
    }
    final String token = new PlainJWT(claimsSet).serialize();
    return token;
}
Also used : PlainJWT(com.nimbusds.jwt.PlainJWT) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet)

Example 4 with PlainJWT

use of com.nimbusds.jwt.PlainJWT in project nifi by apache.

the class KnoxServiceTest method testPlainJwt.

@Test(expected = ParseException.class)
public void testPlainJwt() throws Exception {
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair pair = keyGen.generateKeyPair();
    final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
    final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("user-1").expirationTime(expiration).build();
    final PlainJWT plainJWT = new PlainJWT(claimsSet);
    final KnoxConfiguration configuration = getConfiguration(publicKey);
    final KnoxService service = new KnoxService(configuration);
    service.getAuthenticationFromToken(plainJWT.serialize());
}
Also used : KeyPair(java.security.KeyPair) PlainJWT(com.nimbusds.jwt.PlainJWT) RSAPublicKey(java.security.interfaces.RSAPublicKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) KeyPairGenerator(java.security.KeyPairGenerator) Date(java.util.Date) Test(org.junit.Test)

Aggregations

PlainJWT (com.nimbusds.jwt.PlainJWT)4 JWT (com.nimbusds.jwt.JWT)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)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 EncryptedJWT (com.nimbusds.jwt.EncryptedJWT)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 KeyPair (java.security.KeyPair)1 KeyPairGenerator (java.security.KeyPairGenerator)1 RSAPublicKey (java.security.interfaces.RSAPublicKey)1 ParseException (java.text.ParseException)1 Date (java.util.Date)1 JSONObject (net.minidev.json.JSONObject)1 Test (org.junit.Test)1 CredentialsException (org.pac4j.core.exception.CredentialsException)1 EncryptionConfiguration (org.pac4j.jwt.config.encryption.EncryptionConfiguration)1 SignatureConfiguration (org.pac4j.jwt.config.signature.SignatureConfiguration)1