Search in sources :

Example 41 with JWT

use of com.auth0.android.jwt.JWT in project drug-formulary-ri by HL7-DaVinci.

the class AuthUtils method authCodeIsValid.

/**
 * Verify the authorization code provided in the POST request's claim to /token
 * path
 *
 * @param code        - the authorization code provided in the request
 * @param baseUrl     - this server base URL
 * @param redirectURI - the requestor/client redirect URI provided in the POST
 *                    request
 * @param clientId    - the client ID retrieved from the request's Authorization
 *                    Header
 * @return patientId if the authorization code is valid, otherwise null
 */
public static String authCodeIsValid(String code, String baseUrl, String redirectURI, String clientId) {
    String patientId = null;
    try {
        Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(baseUrl).withAudience(baseUrl).withClaim(REDIRECT_URI_KEY, redirectURI).withClaim(CLIENT_ID_KEY, clientId).build();
        DecodedJWT jwt = verifier.verify(code);
        String username = jwt.getClaim("username").asString();
        User user = User.getUser(username);
        patientId = user != null ? user.getPatientId() : null;
    } catch (SignatureVerificationException | InvalidClaimException e) {
        logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Signature invalid or claim value invalid", e);
    } catch (AlgorithmMismatchException e) {
        logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Algorithm mismatch", e);
    } catch (TokenExpiredException e) {
        logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Token expired", e);
    } catch (JWTVerificationException e) {
        logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Please obtain a new code", e);
    }
    return patientId;
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) InvalidClaimException(com.auth0.jwt.exceptions.InvalidClaimException) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) AlgorithmMismatchException(com.auth0.jwt.exceptions.AlgorithmMismatchException)

Example 42 with JWT

use of com.auth0.android.jwt.JWT in project apigee-config-maven-plugin by apigee.

the class RestUtil method isValidBearerToken.

/**
 * This method is used to validate the Bearer token. It validates the source and
 * the expiration and if the token is about to expire in 30 seconds, set as
 * invalid token
 *
 * @param accessToken
 * @param profile
 * @param clientId
 * @return
 * @throws IOException
 */
private boolean isValidBearerToken(String accessToken, ServerProfile profile, String clientId) throws IOException {
    boolean isValid = false;
    try {
        JWT jwt = JWT.decode(accessToken);
        String jwtClientId = jwt.getClaim("client_id").asString();
        String jwtEmailId = jwt.getClaim("email").asString();
        long jwtExpiresAt = jwt.getExpiresAt().getTime() / 1000;
        long difference = jwtExpiresAt - (System.currentTimeMillis() / 1000);
        if (jwt != null && jwtClientId != null && jwtClientId.equals(clientId) && jwtEmailId != null && jwtEmailId.equalsIgnoreCase(profile.getCredential_user()) && profile.getTokenUrl().contains(jwt.getIssuer()) && difference >= 30) {
            isValid = true;
        }
    } catch (JWTDecodeException exception) {
        throw new IOException(exception.getMessage());
    }
    return isValid;
}
Also used : JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) JWT(com.auth0.jwt.JWT) IOException(java.io.IOException)

Example 43 with JWT

use of com.auth0.android.jwt.JWT in project goobi-workflow by intranda.

the class JwtHelper method verifyTokenWithRotationTime.

private static DecodedJWT verifyTokenWithRotationTime(String token, String secret, long lastRotationTime) {
    Algorithm algorithm = Algorithm.HMAC256(secret + lastRotationTime);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer("Goobi").build();
    DecodedJWT jwt = verifier.verify(token);
    return jwt;
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 44 with JWT

use of com.auth0.android.jwt.JWT in project goobi-workflow by intranda.

the class JwtHelper method createToken.

public static String createToken(Map<String, String> map, Date expiryDate) throws ConfigurationException {
    String secret = ConfigurationHelper.getInstance().getJwtSecret();
    if (secret == null) {
        throw new ConfigurationException("Could not get JWT secret from configuration. Please configure the key 'jwtSecret' in the file goobi_config.properties");
    }
    if (map == null || map.isEmpty()) {
        throw new ConfigurationException("Could not generate token from an empty map.");
    }
    Algorithm algorithm = createSigningAlgorithm(secret);
    Builder tokenBuilder = JWT.create().withIssuer("Goobi");
    for (String key : map.keySet()) {
        tokenBuilder = tokenBuilder.withClaim(key, map.get(key));
    }
    return tokenBuilder.withExpiresAt(expiryDate).sign(algorithm);
}
Also used : ConfigurationException(javax.naming.ConfigurationException) Builder(com.auth0.jwt.JWTCreator.Builder) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 45 with JWT

use of com.auth0.android.jwt.JWT in project goobi-workflow by intranda.

the class AuthorizationFilter method checkJwt.

/**
 * Verifies the JSON web token and checks if the "api_path" and "api_methods" claims match the actual request
 *
 * @param jwt
 * @param path the endpoint path the request tries to use
 * @param method the HTTP method used in the request
 * @return true, if the JWT authorizes the usage of the API path and method. Else: false
 */
public static boolean checkJwt(String jwt, String path, String method) {
    if (StringUtils.isBlank(jwt)) {
        return false;
    }
    try {
        DecodedJWT decodedJWT = JwtHelper.verifyTokenAndReturnClaims(jwt);
        Claim pathClaim = decodedJWT.getClaim("api_path");
        if (pathClaim == null || pathClaim.isNull()) {
            return false;
        }
        if (!Pattern.matches(pathClaim.asString(), path)) {
            return false;
        }
        Claim methodsClaim = decodedJWT.getClaim("api_methods");
        if (methodsClaim == null) {
            return false;
        }
        boolean methodMatch = Arrays.stream(methodsClaim.asArray(String.class)).anyMatch(claimMethod -> method.equalsIgnoreCase(claimMethod));
        if (!methodMatch) {
            return false;
        }
        return true;
    } catch (javax.naming.ConfigurationException | JWTVerificationException e) {
        log.error(e);
        return false;
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)305 Test (org.junit.Test)217 Algorithm (com.auth0.jwt.algorithms.Algorithm)110 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)82 JWTVerifier (com.auth0.jwt.JWTVerifier)79 IOException (java.io.IOException)60 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)54 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)53 Date (java.util.Date)50 Claim (com.auth0.jwt.interfaces.Claim)36 RSAPublicKey (java.security.interfaces.RSAPublicKey)34 ECPublicKey (java.security.interfaces.ECPublicKey)27 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)26 HashMap (java.util.HashMap)25 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)20 Instant (java.time.Instant)20 JsonObject (com.google.gson.JsonObject)19 ServletException (javax.servlet.ServletException)19 JWT (com.auth0.jwt.JWT)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18