Search in sources :

Example 11 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project supertokens-core by supertokens.

the class JWKSAPITest2_9 method testThatKeyFromResponseCanBeUsedForJWTVerification.

/**
 * Test that the JWK with the same kid as the JWT header can be used to verify the JWT signature
 */
@Test
public void testThatKeyFromResponseCanBeUsedForJWTVerification() throws Exception {
    String[] args = { "../" };
    TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));
    JsonObject requestBody = new JsonObject();
    requestBody.addProperty("algorithm", "rs256");
    requestBody.addProperty("jwksDomain", "http://localhost");
    requestBody.add("payload", new JsonObject());
    requestBody.addProperty("validity", 3600);
    JsonObject jwtResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/jwt", requestBody, 1000, 1000, null, Utils.getCdiVersion2_9ForTests(), "jwt");
    String jwt = jwtResponse.get("jwt").getAsString();
    DecodedJWT decodedJWT = JWT.decode(jwt);
    String keyIdFromHeader = decodedJWT.getHeaderClaim("kid").asString();
    JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersion2_9ForTests(), "jwt");
    JsonArray keys = response.getAsJsonArray("keys");
    JsonObject keyToUse = null;
    for (int i = 0; i < keys.size(); i++) {
        JsonObject currentKey = keys.get(i).getAsJsonObject();
        if (currentKey.get("kid").getAsString().equals(keyIdFromHeader)) {
            keyToUse = currentKey;
            break;
        }
    }
    assert keyToUse != null;
    String modulusString = keyToUse.get("n").getAsString();
    String exponentString = keyToUse.get("e").getAsString();
    BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(modulusString));
    BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(exponentString));
    RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent));
    Algorithm verificationAlgorithm = Algorithm.RSA256(new RSAKeyProvider() {

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

        @Override
        public RSAPrivateKey getPrivateKey() {
            return null;
        }

        @Override
        public String getPrivateKeyId() {
            return null;
        }
    });
    JWTVerifier verifier = JWT.require(verificationAlgorithm).build();
    verifier.verify(jwt);
    process.kill();
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));
}
Also used : TestingProcessManager(io.supertokens.test.TestingProcessManager) RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) JsonObject(com.google.gson.JsonObject) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) Algorithm(com.auth0.jwt.algorithms.Algorithm) JsonArray(com.google.gson.JsonArray) RSAPublicKey(java.security.interfaces.RSAPublicKey) BigInteger(java.math.BigInteger) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWTVerifier(com.auth0.jwt.JWTVerifier) Test(org.junit.Test)

Example 12 with JWTVerifier

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

the class IntrospectionEndpoint method handleIntrospection.

public static ResponseEntity<String> handleIntrospection(String token) {
    JSONObject response = new JSONObject();
    String baseUrl = AuthUtils.getFhirBaseUrl();
    try {
        Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(baseUrl).withAudience(baseUrl).build();
        DecodedJWT jwt = verifier.verify(token);
        response.put("active", true);
        response.put("aud", jwt.getAudience().get(0));
        response.put("iss", jwt.getIssuer());
        // Display in sec not ms
        response.put("exp", jwt.getExpiresAt().getTime() / 1000);
        // Display in sec not ms
        response.put("iat", jwt.getIssuedAt().getTime() / 1000);
        response.put("patient_id", jwt.getClaim("patient_id").asString());
    } catch (JWTVerificationException exception) {
        response.put("active", false);
    }
    return new ResponseEntity<>(response.toString(), HttpStatus.OK);
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ResponseEntity(org.springframework.http.ResponseEntity) JSONObject(org.json.JSONObject) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 13 with JWTVerifier

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

the class PatientAuthorizationInterceptor method verify.

/**
 * Helper method to verify and decode the access token
 *
 * @param token       - the access token
 * @param fhirBaseUrl - the base url of this FHIR server
 * @return the base interface Patient ID datatype if the jwt token is verified
 *         and contains a patient ID in it claim, otherwise null.
 * @throws SignatureVerificationException
 * @throws TokenExpiredException
 * @throws JWTVerificationException
 */
private IIdType verify(String token, String fhirBaseUrl) throws SignatureVerificationException, TokenExpiredException, JWTVerificationException {
    Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
    logger.fine("Verifying JWT token iss and aud is " + fhirBaseUrl);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer(fhirBaseUrl).withAudience(fhirBaseUrl).build();
    DecodedJWT jwt = verifier.verify(token);
    String patientId = jwt.getClaim("patient_id").asString();
    if (patientId != null)
        return new IdType("Patient", patientId);
    return null;
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IIdType(org.hl7.fhir.instance.model.api.IIdType) IdType(org.hl7.fhir.r4.model.IdType)

Example 14 with JWTVerifier

use of com.auth0.jwt.JWTVerifier 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 15 with JWTVerifier

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

Aggregations

JWTVerifier (com.auth0.jwt.JWTVerifier)115 Algorithm (com.auth0.jwt.algorithms.Algorithm)104 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)100 Test (org.junit.Test)42 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)30 IOException (java.io.IOException)23 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)18 RSAPublicKey (java.security.interfaces.RSAPublicKey)15 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)14 Claim (com.auth0.jwt.interfaces.Claim)10 Date (java.util.Date)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HashMap (java.util.HashMap)8 ECKey (java.security.interfaces.ECKey)7 ServletException (javax.servlet.ServletException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)5 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)5 URL (java.net.URL)5 KeyFactory (java.security.KeyFactory)5