Search in sources :

Example 51 with Claim

use of com.auth0.jwt.Claim in project ofbiz-framework by apache.

the class JWTManager method validateToken.

/**
 * Validates the provided token using the secret key.
 * If the token is valid it will get the conteined claims and return them.
 * If token validation failed it will return an error.
 * Public for API access from third party code.
 * @param jwtToken the JWT token
 * @param key the server side key to verify the signature
 * @return Map of the claims contained in the token or an error
 */
public static Map<String, Object> validateToken(String jwtToken, String key) {
    Map<String, Object> result = new HashMap<>();
    if (UtilValidate.isEmpty(jwtToken) || UtilValidate.isEmpty(key)) {
        String msg = "JWT token or key can not be empty.";
        Debug.logError(msg, MODULE);
        return ServiceUtil.returnError(msg);
    }
    try {
        JWTVerifier verifToken = JWT.require(Algorithm.HMAC512(key)).withIssuer("ApacheOFBiz").build();
        DecodedJWT jwt = verifToken.verify(jwtToken);
        Map<String, Claim> claims = jwt.getClaims();
        // OK, we can trust this JWT
        for (Map.Entry<String, Claim> entry : claims.entrySet()) {
            result.put(entry.getKey(), entry.getValue().asString());
        }
        return result;
    } catch (JWTVerificationException e) {
        // signature not valid or token expired
        Debug.logError(e.getMessage(), MODULE);
        return ServiceUtil.returnError(e.getMessage());
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) HashMap(java.util.HashMap) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) HashMap(java.util.HashMap) Map(java.util.Map) Claim(com.auth0.jwt.interfaces.Claim)

Example 52 with Claim

use of com.auth0.jwt.Claim in project litemall by linlinjava.

the class JwtHelper method verifyTokenAndGetUserId.

public Integer verifyTokenAndGetUserId(String token) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUSER).build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        Claim claim = claims.get("userId");
        return claim.asInt();
    } catch (JWTVerificationException exception) {
    // exception.printStackTrace();
    }
    return 0;
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 53 with Claim

use of com.auth0.jwt.Claim in project opencast by opencast.

the class JWTVerifierTest method testVerifyAsymmetric.

@Test
public void testVerifyAsymmetric() throws Exception {
    DecodedJWT decodedJWT;
    // Valid JWT + valid claim constraints
    decodedJWT = JWTVerifier.verify(generator.generateValidAsymmetricJWT(), validProvider, generator.generateValidClaimConstraints());
    assertEquals(generator.getUsername(), decodedJWT.getClaim("username").asString());
    // Valid JWT + invalid claim constraints
    assertThrows(JWTVerificationException.class, () -> JWTVerifier.verify(generator.generateValidAsymmetricJWT(), validProvider, generator.generateInvalidClaimConstraints()));
    // Valid JWT + invalid provider
    assertThrows(JWTVerificationException.class, () -> JWTVerifier.verify(generator.generateValidAsymmetricJWT(), invalidProvider, generator.generateValidClaimConstraints()));
    // Invalid JWT
    assertThrows(JWTVerificationException.class, () -> JWTVerifier.verify(generator.generateExpiredAsymmetricJWT(), validProvider, generator.generateValidClaimConstraints()));
    // Simulate key rotation
    decodedJWT = JWTVerifier.verify(generator.generateValidAsymmetricJWT(), rotatingProvider, generator.generateValidClaimConstraints());
    assertEquals(generator.getUsername(), decodedJWT.getClaim("username").asString());
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Test(org.junit.Test)

Example 54 with Claim

use of com.auth0.jwt.Claim in project hopsworks by logicalclocks.

the class JWTController method invalidateServiceToken.

public void invalidateServiceToken(String serviceToken2invalidate, String defaultJWTSigningKeyName) {
    DecodedJWT serviceJWT2invalidate = decodeToken(serviceToken2invalidate);
    try {
        invalidate(serviceToken2invalidate);
    } catch (InvalidationException ex) {
        LOGGER.log(Level.WARNING, "Could not invalidate service JWT with ID " + serviceJWT2invalidate.getId() + ". Continuing with deleting signing key");
    }
    Claim signingKeyID = serviceJWT2invalidate.getClaim(Constants.SERVICE_JWT_RENEWAL_KEY_ID);
    if (signingKeyID != null && !signingKeyID.isNull()) {
        // Do not use Claim.asInt, it returns null
        JwtSigningKey signingKey = findSigningKeyById(Integer.parseInt(signingKeyID.asString()));
        if (signingKey != null && defaultJWTSigningKeyName != null) {
            if (!defaultJWTSigningKeyName.equals(signingKey.getName()) && !ONE_TIME_JWT_SIGNING_KEY_NAME.equals(signingKey.getName())) {
                deleteSigningKey(signingKey.getName());
            }
        }
    }
}
Also used : JwtSigningKey(io.hops.hopsworks.persistence.entity.jwt.JwtSigningKey) InvalidationException(io.hops.hopsworks.jwt.exception.InvalidationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 55 with Claim

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

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