Search in sources :

Example 16 with Verification

use of com.auth0.jwt.interfaces.Verification in project snow-owl by b2ihealthcare.

the class IdentityPlugin method configureJWT.

@VisibleForTesting
/*package*/
void configureJWT(ApplicationContext services, final IdentityProvider identityProvider, final IdentityConfiguration conf) throws MalformedURLException {
    RSAKeyProvider rsaKeyProvider = createRSAKeyProvider(conf);
    Algorithm algorithm;
    if (!Strings.isNullOrEmpty(conf.getJws())) {
        algorithm = SUPPORTED_JWS_ALGORITHMS.getOrDefault(conf.getJws(), this::throwUnsupportedJws).apply(conf, rsaKeyProvider);
    } else {
        IdentityProvider.LOG.warn("'identity.jws' configuration is missing, disabling JWT authorization token signing and verification.");
        algorithm = null;
    }
    JWTGenerator generator;
    JWTVerifier verifier;
    if (algorithm == null) {
        // both signing and verification is disabled
        generator = JWT_GENERATOR_DISABLED;
        verifier = JWT_VERIFIER_DISABLED;
    } else if (rsaKeyProvider != null && rsaKeyProvider.getPrivateKey() == null) {
        generator = JWT_GENERATOR_DISABLED;
        verifier = createJWTVerifier(algorithm, conf);
    } else {
        generator = new DefaultJWTGenerator(algorithm, conf);
        verifier = createJWTVerifier(algorithm, conf);
    }
    // always configure a JWTGenerator, a JWTVerifier and an AuthorizationHeader verifier
    services.registerService(JWTGenerator.class, generator);
    services.registerService(JWTVerifier.class, verifier);
    services.registerService(AuthorizationHeaderVerifier.class, new AuthorizationHeaderVerifier(verifier, identityProvider, conf.getEmailClaimProperty(), conf.getPermissionsClaimProperty()));
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 17 with Verification

use of com.auth0.jwt.interfaces.Verification in project snow-owl by b2ihealthcare.

the class IdentityPlugin method createRSAKeyProvider.

private RSAKeyProvider createRSAKeyProvider(IdentityConfiguration conf) throws MalformedURLException {
    final String privateKeyId;
    final RSAPrivateKey privateKey;
    // read private key if provided
    if (!Strings.isNullOrEmpty(conf.getSigningKey())) {
        privateKeyId = Hashing.goodFastHash(16).hashString(conf.getSigningKey(), Charsets.UTF_8).toString();
        privateKey = readPrivateKey(conf.getSigningKey());
    } else {
        privateKeyId = null;
        privateKey = null;
    }
    if (!Strings.isNullOrEmpty(conf.getJwksUrl())) {
        // prefer JSON Web Key Set provider URLs (if set) for token verification
        JwkProvider jwkProvider = new JwkProviderBuilder(new URL(conf.getJwksUrl())).cached(5, 24, TimeUnit.HOURS).rateLimited(10, 1, TimeUnit.MINUTES).build();
        return new RSAKeyProvider() {

            @Override
            public RSAPublicKey getPublicKeyById(String kid) {
                try {
                    return (RSAPublicKey) jwkProvider.get(kid).getPublicKey();
                } catch (JwkException e) {
                    throw new SnowowlRuntimeException(e.getMessage(), e);
                }
            }

            @Override
            public String getPrivateKeyId() {
                return privateKeyId;
            }

            @Override
            public RSAPrivateKey getPrivateKey() {
                return privateKey;
            }
        };
    } else if (!Strings.isNullOrEmpty(conf.getVerificationKey())) {
        // if JWKS is not set, then fall back to verification key if set
        RSAPublicKey publicKey = readPublicKey(conf.getVerificationKey());
        return new RSAKeyProvider() {

            @Override
            public RSAPublicKey getPublicKeyById(String kid) {
                return publicKey;
            }

            @Override
            public String getPrivateKeyId() {
                return privateKeyId;
            }

            @Override
            public RSAPrivateKey getPrivateKey() {
                return privateKey;
            }
        };
    } else {
        // if neither jwksUrl nor the verificationKey settings are configured then this not an RSA configuration (or an invalid configuration raised when creating the algorithm instance)
        return null;
    }
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) RSAPublicKey(java.security.interfaces.RSAPublicKey) JwkProvider(com.auth0.jwk.JwkProvider) JwkProviderBuilder(com.auth0.jwk.JwkProviderBuilder) JwkException(com.auth0.jwk.JwkException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) URL(java.net.URL) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Example 18 with Verification

use of com.auth0.jwt.interfaces.Verification in project open-kilda by telstra.

the class PathVerificationService method parseDiscoveryPacket.

@VisibleForTesting
DiscoveryPacketData parseDiscoveryPacket(DiscoveryPacket discoveryPacket, long switchLatency) {
    ByteBuffer portBb = ByteBuffer.wrap(discoveryPacket.getPortId().getValue());
    portBb.position(1);
    OFPort remotePort = OFPort.of(portBb.getShort());
    DiscoveryPacketData.DiscoveryPacketDataBuilder builder = DiscoveryPacketData.builder();
    builder.remotePort(remotePort);
    builder.pathOrdinal(10);
    builder.switchT0(-1);
    builder.switchT1(-1);
    for (LLDPTLV lldptlv : discoveryPacket.getOptionalTlvList()) {
        if (matchOptionalLldptlv(lldptlv, REMOTE_SWITCH_OPTIONAL_TYPE, 12)) {
            ByteBuffer dpidBb = ByteBuffer.wrap(lldptlv.getValue());
            builder.remoteSwitchId(DatapathId.of(dpidBb.getLong(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES)));
        } else if (matchOptionalLldptlv(lldptlv, TIMESTAMP_OPTIONAL_TYPE, 12)) {
            // skip OpenFlow OUI (4 bytes above)
            ByteBuffer tsBb = ByteBuffer.wrap(lldptlv.getValue());
            long sendTime = tsBb.getLong(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES);
            // include the RX switch latency to "subtract" it
            builder.timestamp(sendTime + switchLatency);
        } else if (matchOptionalLldptlv(lldptlv, PATH_ORDINAL_OPTIONAL_TYPE, 8)) {
            ByteBuffer typeBb = ByteBuffer.wrap(lldptlv.getValue());
            builder.pathOrdinal(typeBb.getInt(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES));
        } else if (matchOptionalLldptlv(lldptlv, SWITCH_T0_OPTIONAL_TYPE, 12)) {
            builder.switchT0(noviflowTimestamp(Arrays.copyOfRange(lldptlv.getValue(), LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES, lldptlv.getValue().length)));
        } else if (matchOptionalLldptlv(lldptlv, SWITCH_T1_OPTIONAL_TYPE, 12)) {
            builder.switchT1(noviflowTimestamp(Arrays.copyOfRange(lldptlv.getValue(), LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES, lldptlv.getValue().length)));
        } else if (matchOptionalLldptlv(lldptlv, TOKEN_OPTIONAL_TYPE)) {
            ByteBuffer bb = ByteBuffer.wrap(lldptlv.getValue());
            bb.position(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES);
            byte[] tokenArray = new byte[lldptlv.getLength() - LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES];
            bb.get(tokenArray, 0, tokenArray.length);
            String token = new String(tokenArray);
            try {
                DecodedJWT jwt = verifier.verify(token);
                Claim idClaim = jwt.getClaim("id");
                if (!idClaim.isNull()) {
                    builder.packetId(idClaim.asLong());
                }
                builder.signed(true);
            } catch (JWTVerificationException e) {
                logger.error("Packet verification failed", e);
                builder.signed(false);
            }
        }
    }
    return builder.build();
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) OFPort(org.projectfloodlight.openflow.types.OFPort) ByteBuffer(java.nio.ByteBuffer) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim) LLDPTLV(net.floodlightcontroller.packet.LLDPTLV) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 19 with Verification

use of com.auth0.jwt.interfaces.Verification in project java-docs-samples by GoogleCloudPlatform.

the class VerifyingInstance method verifyToken.

void verifyToken(String token) {
    TokenVerifier gtv = new TokenVerifier();
    // Following are examples how to handle verification failure.
    try {
        DecodedGoogleJWTWrapper decodedJwt = gtv.verifyWithAudience(audience, token);
        System.out.println("Project id : " + decodedJwt.getProjectId());
        System.out.println("Project number : " + decodedJwt.getProjectNumber());
    // This are examples how to handle exceptions, which indicate verification failure.
    } catch (AlgorithmMismatchException e) {
        // We assume that downloaded certs are RSA256, this exception will happen if this changes.
        throw e;
    } catch (SignatureVerificationException e) {
        // Could not verify signature of a token, possibly someone provided forged token.
        throw e;
    } catch (TokenExpiredException e) {
        // We encountered old token, possibly replay attack.
        throw e;
    } catch (InvalidClaimException e) {
        // Different Audience for token and for verification, possibly token for other verifier.
        throw e;
    } catch (JWTVerificationException e) {
        // - InvalidClaimException
        throw e;
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) TokenVerifier(com.example.compute.signedmetadata.token.TokenVerifier) DecodedGoogleJWTWrapper(com.example.compute.signedmetadata.token.DecodedGoogleJWTWrapper) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) InvalidClaimException(com.auth0.jwt.exceptions.InvalidClaimException) AlgorithmMismatchException(com.auth0.jwt.exceptions.AlgorithmMismatchException)

Example 20 with Verification

use of com.auth0.jwt.interfaces.Verification in project hopsworks by logicalclocks.

the class JWTFilter method jwtFilter.

public void jwtFilter(ContainerRequestContext requestContext) throws IOException {
    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
    Object responseEntity;
    if (authorizationHeader == null) {
        LOGGER.log(Level.FINEST, "Authorization header not set.");
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Authorization header not set.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    if (!authorizationHeader.startsWith(BEARER)) {
        LOGGER.log(Level.FINEST, "Invalid token. AuthorizationHeader : {0}", authorizationHeader);
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    String token = authorizationHeader.substring(BEARER.length()).trim();
    DecodedJWT jwt = JWT.decode(token);
    Claim expLeewayClaim = jwt.getClaim(EXPIRY_LEEWAY);
    String issuer = getIssuer();
    int expLeeway = expLeewayClaim.asInt();
    try {
        Algorithm algorithm = getAlgorithm(jwt);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer == null || issuer.isEmpty() ? jwt.getIssuer() : issuer).acceptExpiresAt(expLeeway == 0 ? DEFAULT_EXPIRY_LEEWAY : expLeeway).build();
        jwt = verifier.verify(token);
    } catch (Exception exception) {
        LOGGER.log(Level.FINE, "JWT Verification Exception: {0}", exception.getMessage());
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, exception.getMessage());
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    if (!isTokenValid(jwt)) {
        LOGGER.log(Level.FINEST, "JWT Verification Exception: Invalidated token.");
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    Claim rolesClaim = jwt.getClaim(ROLES);
    String[] userRoles = rolesClaim == null ? new String[0] : rolesClaim.asArray(String.class);
    Set<String> allowedRolesSet = allowedRoles();
    if (allowedRolesSet != null && !allowedRolesSet.isEmpty()) {
        if (!intersect(allowedRolesSet, Arrays.asList(userRoles))) {
            LOGGER.log(Level.FINE, "JWT Access Exception: Client not authorized for this invocation.");
            responseEntity = responseEntity(Response.Status.FORBIDDEN, "Client not authorized for this invocation.");
            requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
            return;
        }
    }
    List<String> audience = jwt.getAudience();
    Set<String> accepts = acceptedTokens();
    if (accepts != null && !accepts.isEmpty()) {
        if (!intersect(accepts, audience)) {
            LOGGER.log(Level.FINE, "JWT Access Exception: Token not issued for this recipient.");
            responseEntity = responseEntity(Response.Status.FORBIDDEN, "Token not issued for this recipient.");
            requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
            return;
        }
    }
    postJWTFilter(requestContext, jwt);
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) Claim(com.auth0.jwt.interfaces.Claim) IOException(java.io.IOException) SigningKeyNotFoundException(io.hops.hopsworks.jwt.exception.SigningKeyNotFoundException)

Aggregations

Test (org.junit.Test)29 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)28 Algorithm (com.auth0.jwt.algorithms.Algorithm)14 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)11 Date (java.util.Date)11 Verification (com.auth0.jwt.interfaces.Verification)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 JWTVerifier (com.auth0.jwt.JWTVerifier)5 RSAPublicKey (java.security.interfaces.RSAPublicKey)5 Job (com.auth0.json.mgmt.jobs.Job)4 Claim (com.auth0.jwt.interfaces.Claim)4 Clock (com.auth0.jwt.interfaces.Clock)4 List (java.util.List)4 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)4 JWT (com.auth0.jwt.JWT)3 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)3 FloodlightModuleException (net.floodlightcontroller.core.module.FloodlightModuleException)3