Search in sources :

Example 6 with JoseException

use of org.jose4j.lang.JoseException in project blueocean-plugin by jenkinsci.

the class JwtTokenVerifierImpl method validate.

/**
 * @return
 *      null if the JWT token is not present
 * @throws Exception
 *      if the JWT token is present but invalid
 */
@CheckForNull
private Authentication validate(HttpServletRequest request) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        return null;
    }
    String token = authHeader.substring("Bearer ".length());
    JsonWebStructure jws = parse(token);
    if (jws == null) {
        return null;
    }
    try {
        String alg = jws.getAlgorithmHeaderValue();
        if (alg == null || !alg.equals(RSA_USING_SHA256)) {
            logger.error(String.format("Invalid JWT token: unsupported algorithm in header, found %s, expected %s", alg, RSA_USING_SHA256));
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        }
        String kid = jws.getKeyIdHeaderValue();
        if (kid == null) {
            logger.error("Invalid JWT token: missing kid");
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        }
        SigningPublicKey publicKey = JwtSigningKeyProvider.toPublicKey(kid);
        if (publicKey == null) {
            throw new ServiceException.UnexpectedErrorException("Invalid kid=" + kid);
        }
        JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setRequireJwtId().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
        30).setRequireSubject().setVerificationKey(// verify the sign with the public key
        publicKey.getKey()).build();
        try {
            JwtContext context = jwtConsumer.process(token);
            JwtClaims claims = context.getJwtClaims();
            String subject = claims.getSubject();
            if (subject.equals("anonymous")) {
                // if anonymous, we do not bother checking expiration
                return Jenkins.ANONYMOUS2;
            } else {
                // If not anonymous user, get Authentication object associated with this claim
                // We give a change to the authentication store to inspect the claims and if expired it might
                // do cleanup of associated Authentication object for example.
                JwtAuthenticationStore authenticationStore = getJwtStore(claims.getClaimsMap());
                Authentication authentication = authenticationStore.getAuthentication(claims.getClaimsMap());
                // Now check if token expired
                NumericDate expirationTime = claims.getExpirationTime();
                if (expirationTime.isBefore(NumericDate.now())) {
                    throw new ServiceException.UnauthorizedException("Invalid JWT token: expired");
                }
                return authentication;
            }
        } catch (InvalidJwtException e) {
            logger.error("Invalid JWT token: " + e.getMessage(), e);
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        } catch (MalformedClaimException e) {
            logger.error(String.format("Error reading sub header for token %s", jws.getPayload()), e);
            throw new ServiceException.UnauthorizedException("Invalid JWT token: malformed claim");
        }
    } catch (JoseException e) {
        logger.error("Error parsing JWT token: " + e.getMessage(), e);
        throw new ServiceException.UnauthorizedException("Invalid JWT Token: " + e.getMessage());
    }
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) SigningPublicKey(io.jenkins.blueocean.auth.jwt.SigningPublicKey) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JoseException(org.jose4j.lang.JoseException) JwtContext(org.jose4j.jwt.consumer.JwtContext) JwtAuthenticationStore(io.jenkins.blueocean.auth.jwt.JwtAuthenticationStore) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) ServiceException(io.jenkins.blueocean.commons.ServiceException) Authentication(org.springframework.security.core.Authentication) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) CheckForNull(javax.annotation.CheckForNull)

Example 7 with JoseException

use of org.jose4j.lang.JoseException in project open-ecard by ecsec.

the class TCTokenVerifier method verifyRequestToken.

/**
 * Verifies the elements of the TCToken.
 *
 * @throws InvalidRedirectUrlException Thrown in case the RefreshAddress is missing or invalid.
 * @throws InvalidTCTokenElement Thrown in case any element inside the TCToken is invalid.
 */
public void verifyRequestToken() throws InvalidRedirectUrlException, InvalidTCTokenElement {
    assertRefreshURL(token.getRefreshAddress());
    assertHttpsURL("ServerAddress", token.getServerAddress());
    assertRequired("SessionIdentifier", token.getSessionIdentifier());
    assertRequired("PathSecurity-Protocol", token.getPathSecurityProtocol());
    checkEqualOR("PathSecurity-Protocol", token.getPathSecurityProtocol(), "urn:ietf:rfc:5246", "http://ws.openecard.org/pathsecurity/tlsv12-with-pin-encryption");
    if (token.getPathSecurityProtocol().equals("http://ws.openecard.org/pathsecurity/tlsv12-with-pin-encryption")) {
        assertRequired("PathSecurity-Parameters", token.getPathSecurityParameters());
        assertRequired("JWK", token.getPathSecurityParameters().getJWK());
        try {
            JsonWebKey key = JsonWebKey.Factory.newJwk(token.getPathSecurityParameters().getJWK());
        } catch (JoseException ex) {
            throw new InvalidTCTokenElement("Failed to parse JWK.", ex);
        }
    }
}
Also used : JoseException(org.jose4j.lang.JoseException) InvalidTCTokenElement(org.openecard.addons.cg.ex.InvalidTCTokenElement) JsonWebKey(org.jose4j.jwk.JsonWebKey)

Example 8 with JoseException

use of org.jose4j.lang.JoseException in project open-ecard by ecsec.

the class ChipGateway method getPin.

@Nullable
private char[] getPin(@Nullable String encryptedPin) throws RemotePinException {
    if (ChipGatewayProperties.isRemotePinAllowed() && encryptedPin != null) {
        if (pinKey != null) {
            try {
                // decrypt PIN
                JsonWebEncryption jwe = new JsonWebEncryption();
                // specify algorithmic constraints
                AlgorithmConstraints algConstraints = new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, KeyManagementAlgorithmIdentifiers.DIRECT);
                jwe.setAlgorithmConstraints(algConstraints);
                AlgorithmConstraints encConstraints = new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256, ContentEncryptionAlgorithmIdentifiers.AES_192_CBC_HMAC_SHA_384, ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512, ContentEncryptionAlgorithmIdentifiers.AES_128_GCM, ContentEncryptionAlgorithmIdentifiers.AES_192_GCM, ContentEncryptionAlgorithmIdentifiers.AES_256_GCM);
                jwe.setContentEncryptionAlgorithmConstraints(encConstraints);
                // perform decryption
                jwe.setCompactSerialization(encryptedPin);
                jwe.setKey(pinKey.getKey());
                byte[] pinBytes = jwe.getPlaintextBytes();
                // check if PIN is a sane value
                char[] pin;
                if (pinBytes == null || pinBytes.length == 0) {
                    String msg = "No or empty PIN received from ChipGateway server, despite a key being present.";
                    LOG.warn(msg);
                    pin = null;
                } else {
                    CharBuffer charBuf = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(pinBytes));
                    pin = new char[charBuf.remaining()];
                    charBuf.get(pin);
                    if (charBuf.hasArray()) {
                        Arrays.fill(charBuf.array(), ' ');
                    }
                }
                return pin;
            } catch (JoseException ex) {
                throw new RemotePinException("Error decrypting PIN.", ex);
            }
        } else {
            // PIN sent but no key provided, raise error for the server
            throw new RemotePinException("Encrypted PIN received, but no key for decryption is available.");
        }
    } else {
        // no pin sent, let user supply the pin
        return null;
    }
}
Also used : RemotePinException(org.openecard.addons.cg.ex.RemotePinException) JoseException(org.jose4j.lang.JoseException) CharBuffer(java.nio.CharBuffer) JsonWebEncryption(org.jose4j.jwe.JsonWebEncryption) AlgorithmConstraints(org.jose4j.jwa.AlgorithmConstraints) Nullable(javax.annotation.Nullable)

Example 9 with JoseException

use of org.jose4j.lang.JoseException in project box-java-sdk by box.

the class BoxDeveloperEditionAPIConnection method constructJWTAssertion.

private String constructJWTAssertion(NumericDate now) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(this.getClientID());
    claims.setAudience(JWT_AUDIENCE);
    if (now == null) {
        claims.setExpirationTimeMinutesInTheFuture(0.5f);
    } else {
        now.addSeconds(30L);
        claims.setExpirationTime(now);
    }
    claims.setSubject(this.entityID);
    claims.setClaim("box_sub_type", this.entityType.toString());
    claims.setGeneratedJwtId(64);
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(this.decryptPrivateKey());
    jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier());
    jws.setHeader("typ", "JWT");
    if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) {
        jws.setHeader("kid", this.publicKeyID);
    }
    String assertion;
    try {
        assertion = jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new BoxAPIException("Error serializing JSON Web Token assertion.", e);
    }
    return assertion;
}
Also used : JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException)

Example 10 with JoseException

use of org.jose4j.lang.JoseException in project habot by ghys.

the class NotificationService method sendNotification.

/**
 * Sends a web push notification to a specified subscription
 *
 * @param subscription the subscription to send the notification to
 * @param payload the payload to push
 * @return the {@link Future} for the {@link Response} to the push server
 * @throws GeneralSecurityException
 */
public Future<Response> sendNotification(Subscription subscription, String payload) throws GeneralSecurityException {
    getPushService();
    Notification notification = new Notification(subscription, payload);
    try {
        return this.pushService.send(notification);
    } catch (IOException | JoseException | ExecutionException | InterruptedException e) {
        logger.error("Unable to send the notification to {}: {}", this.subscriptionProvider.keyToString(subscription.keys), e.toString());
        return null;
    }
}
Also used : JoseException(org.jose4j.lang.JoseException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Notification(org.openhab.ui.habot.notification.internal.webpush.Notification)

Aggregations

JoseException (org.jose4j.lang.JoseException)17 JwtClaims (org.jose4j.jwt.JwtClaims)7 IOException (java.io.IOException)6 JsonWebKey (org.jose4j.jwk.JsonWebKey)6 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)5 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)5 JsonWebSignature (org.jose4j.jws.JsonWebSignature)4 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)4 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)4 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 NumericDate (org.jose4j.jwt.NumericDate)3 StringReader (java.io.StringReader)2 Map (java.util.Map)2 DeploymentException (javax.enterprise.inject.spi.DeploymentException)2 JsonObject (javax.json.JsonObject)2 JsonParsingException (javax.json.stream.JsonParsingException)2 JsonWebKeySet (org.jose4j.jwk.JsonWebKeySet)2 JwtContext (org.jose4j.jwt.consumer.JwtContext)2 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)2 TemplateCall (com.peterphi.std.guice.web.rest.templating.TemplateCall)1