Search in sources :

Example 46 with Claim

use of com.auth0.android.jwt.Claim in project snow-owl by b2ihealthcare.

the class AuthorizationHeaderVerifier method toUser.

/**
 * Converts the given JWT access token to a {@link User} representation using the configured email and permission claims.
 *
 * @param jwt
 *            - the JWT to convert to a {@link User} object
 * @return
 * @throws BadRequestException
 *             - if either the configured email or permissions property is missing from the given JWT
 */
public User toUser(DecodedJWT jwt) {
    final Claim emailClaim = jwt.getClaim(emailClaimProperty);
    if (emailClaim == null || emailClaim.isNull()) {
        throw new BadRequestException("'%s' JWT access token field is required for email access, but it was missing.", emailClaimProperty);
    }
    Claim permissionsClaim = jwt.getClaim(permissionsClaimProperty);
    if (permissionsClaim == null || permissionsClaim.isNull()) {
        throw new BadRequestException("'%s' JWT access token field is required for permissions access, but it was missing.", permissionsClaimProperty);
    }
    final Set<Permission> permissions = jwt.getClaim(permissionsClaimProperty).asList(String.class).stream().map(Permission::valueOf).collect(Collectors.toSet());
    return new User(emailClaim.asString(), List.of(new Role("jwt_roles", permissions)));
}
Also used : BadRequestException(com.b2international.commons.exceptions.BadRequestException) Claim(com.auth0.jwt.interfaces.Claim)

Example 47 with Claim

use of com.auth0.android.jwt.Claim in project java-rest-api by messagebird.

the class RequestValidator method validateSignature.

/**
 * Returns raw signature payload after validating a signature successfully,
 * otherwise throws {@code RequestValidationException}.
 * <p>
 * This JWT is signed with a MessageBird account unique secret key, ensuring the request is from MessageBird and
 * a specific account.
 * The JWT contains the following claims:
 * </p>
 * <ul>
 *   <li>"url_hash" - the raw URL hashed with SHA256 ensuring the URL wasn't altered.</li>
 *   <li> "payload_hash" - the raw payload hashed with SHA256 ensuring the payload wasn't altered.</li>
 *   <li> "jti" - a unique token ID to implement an optional non-replay check (NOT validated by default).</li>
 *   <li> "nbf" - the not before timestamp.</li>
 *   <li> "exp" - the expiration timestamp is ensuring that a request isn't captured and used at a later time.</li>
 *   <li> "iss" - the issuer name, always MessageBird.</li>
 * </ul>
 *
 * @param clock       custom {@link Clock} instance to validate timestamp claims.
 * @param signature   the actual signature.
 * @param url         the raw url including the protocol, hostname and query string,
 *                    {@code https://example.com/?example=42}.
 * @param requestBody the raw request body.
 * @return raw signature payload as {@link DecodedJWT} object.
 * @throws RequestValidationException when the signature is invalid.
 * @see <a href="https://developers.messagebird.com/docs/verify-http-requests">Verify HTTP Requests</a>
 */
public DecodedJWT validateSignature(Clock clock, String signature, String url, byte[] requestBody) throws RequestValidationException {
    if (signature == null || signature.length() == 0)
        throw new RequestValidationException("The signature can not be empty.");
    if (!skipURLValidation && (url == null || url.length() == 0))
        throw new RequestValidationException("The url can not be empty.");
    DecodedJWT jwt = JWT.decode(signature);
    Algorithm algorithm;
    switch(jwt.getAlgorithm()) {
        case "HS256":
            algorithm = HMAC256;
            break;
        case "HS384":
            algorithm = HMAC384;
            break;
        case "HS512":
            algorithm = HMAC512;
            break;
        default:
            throw new RequestValidationException(String.format("The signing method '%s' is invalid.", jwt.getAlgorithm()));
    }
    BaseVerification builder = (BaseVerification) JWT.require(algorithm).withIssuer("MessageBird").ignoreIssuedAt().acceptLeeway(1);
    if (!skipURLValidation)
        builder.withClaim("url_hash", calculateSha256(url.getBytes()));
    boolean payloadHashClaimExist = !jwt.getClaim("payload_hash").isNull();
    if (requestBody != null && requestBody.length > 0) {
        if (!payloadHashClaimExist) {
            throw new RequestValidationException("The Claim 'payload_hash' is not set but payload is present.");
        }
        builder.withClaim("payload_hash", calculateSha256(requestBody));
    } else if (payloadHashClaimExist) {
        throw new RequestValidationException("The Claim 'payload_hash' is set but actual payload is missing.");
    }
    JWTVerifier verifier = clock == null ? builder.build() : builder.build(clock);
    try {
        return verifier.verify(jwt);
    } catch (SignatureVerificationException e) {
        throw new RequestValidationException("Signature is invalid.", e);
    } catch (JWTVerificationException e) {
        throw new RequestValidationException(e.getMessage(), e.getCause());
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) RequestValidationException(com.messagebird.exceptions.RequestValidationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) BaseVerification(com.auth0.jwt.JWTVerifier.BaseVerification)

Example 48 with Claim

use of com.auth0.android.jwt.Claim 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 49 with Claim

use of com.auth0.android.jwt.Claim in project structr by structr.

the class JWTHelper method getPrincipalForAccessTokenWithKeystore.

private static Principal getPrincipalForAccessTokenWithKeystore(String token, PropertyKey<String> eMailKey) throws FrameworkException {
    Key publicKey = getPublicKeyForToken();
    final Algorithm alg = parseAlgorithm(publicKey.getAlgorithm());
    Map<String, Claim> claims = validateTokenWithKeystore(token, alg);
    if (claims == null) {
        return null;
    }
    Principal user = getPrincipalForTokenClaims(claims, eMailKey);
    if (user == null) {
        return null;
    }
    // Check if the access_token is still valid.
    // If access_token isn't valid anymore, then either it timed out, or the user logged out.
    String tokenReference = claims.getOrDefault("tokenId", new NullClaim()).asString();
    if (validateTokenForUser(tokenReference, user)) {
        return user;
    }
    return null;
}
Also used : NullClaim(com.auth0.jwt.impl.NullClaim) Algorithm(com.auth0.jwt.algorithms.Algorithm) RSAPublicKey(java.security.interfaces.RSAPublicKey) PropertyKey(org.structr.core.property.PropertyKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim) Principal(org.structr.core.entity.Principal)

Example 50 with Claim

use of com.auth0.android.jwt.Claim in project structr by structr.

the class JWTHelper method getPrincipalForRefreshToken.

public static Principal getPrincipalForRefreshToken(final String refreshToken) throws FrameworkException {
    final String jwtSecretType = Settings.JWTSecretType.getValue();
    Map<String, Claim> claims = null;
    switch(jwtSecretType) {
        default:
        case "secret":
            final String secret = Settings.JWTSecret.getValue();
            claims = validateTokenWithSecret(refreshToken, secret);
            break;
        case "keypair":
            final RSAPublicKey publicKey = getPublicKeyForToken();
            final RSAPrivateKey privateKey = getPrivateKeyForToken();
            if (publicKey == null || privateKey == null) {
                break;
            }
            claims = validateTokenWithKeystore(refreshToken, Algorithm.RSA256(publicKey, privateKey));
            break;
        case "jwks":
            throw new FrameworkException(400, "will not validate refresh_token because authentication is not handled by this instance");
    }
    if (claims == null) {
        return null;
    }
    final String tokenId = claims.get("tokenId").asString();
    final String tokenType = claims.get("tokenType").asString();
    if (tokenId == null || tokenType == null || !StringUtils.equals(tokenType, "refresh_token")) {
        return null;
    }
    Principal user = AuthHelper.getPrincipalForCredential(StructrApp.key(Principal.class, "refreshTokens"), new String[] { tokenId }, false);
    if (user == null) {
        return null;
    }
    Principal.removeRefreshToken(user, tokenId);
    return user;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) FrameworkException(org.structr.common.error.FrameworkException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim) Principal(org.structr.core.entity.Principal)

Aggregations

Claim (com.auth0.jwt.interfaces.Claim)110 Test (org.junit.Test)67 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)62 JsonNode (com.fasterxml.jackson.databind.JsonNode)42 Algorithm (com.auth0.jwt.algorithms.Algorithm)24 Date (java.util.Date)24 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)21 RSAPublicKey (java.security.interfaces.RSAPublicKey)21 Test (org.junit.jupiter.api.Test)18 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)17 JWTVerifier (com.auth0.jwt.JWTVerifier)15 JwksTestKeySource (org.sdase.commons.server.auth.service.testsources.JwksTestKeySource)14 JsonObject (com.google.gson.JsonObject)10 HashMap (java.util.HashMap)9 UserPojo (com.auth0.jwt.UserPojo)8 IOException (java.io.IOException)8 Map (java.util.Map)8 TestingProcessManager (io.supertokens.test.TestingProcessManager)7 NullClaim (com.auth0.jwt.impl.NullClaim)5 JWT (com.auth0.jwt.JWT)4