Search in sources :

Example 31 with JWT

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

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

the class JWKSAPITest2_9 method testThatKeysContainsMatchingKeyId.

/**
 * Test that after creating a JWT the returned list of JWKs has a JWK with the same key id as the JWT header
 */
@Test
public void testThatKeysContainsMatchingKeyId() 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");
    boolean didFindKey = false;
    for (int i = 0; i < keys.size(); i++) {
        JsonObject currentKey = keys.get(i).getAsJsonObject();
        if (currentKey.get("kid").getAsString().equals(keyIdFromHeader)) {
            didFindKey = true;
            break;
        }
    }
    assert didFindKey;
    process.kill();
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));
}
Also used : JsonArray(com.google.gson.JsonArray) TestingProcessManager(io.supertokens.test.TestingProcessManager) JsonObject(com.google.gson.JsonObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Test(org.junit.Test)

Example 33 with JWT

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

the class JWTSigningAPITest2_9 method testThatDecodedJWTHasCustomPayload.

/**
 * Test that the returned JWT payload contains provided custom payload properties
 */
@Test
public void testThatDecodedJWTHasCustomPayload() 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");
    JsonObject customPayload = new JsonObject();
    customPayload.addProperty("customClaim", "customValue");
    requestBody.add("payload", customPayload);
    requestBody.addProperty("validity", 3600);
    JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/jwt", requestBody, 1000, 1000, null, Utils.getCdiVersion2_9ForTests(), "jwt");
    String jwt = response.get("jwt").getAsString();
    DecodedJWT decodedJWT = JWT.decode(jwt);
    Claim customClaim = decodedJWT.getClaim("customClaim");
    assertTrue(!customClaim.isNull() && customClaim.asString().equals("customValue"));
    process.kill();
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));
}
Also used : TestingProcessManager(io.supertokens.test.TestingProcessManager) JsonObject(com.google.gson.JsonObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim) Test(org.junit.Test)

Example 34 with JWT

use of com.auth0.android.jwt.JWT in project biosamples-v4 by EBIBioSamples.

the class AapClientService method getJwt.

public synchronized String getJwt() {
    if (username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0) {
        return null;
    }
    // TODO refresh token when less than 5 minutes left, rather than when expired
    if (!jwt.isPresent() || (expiry.isPresent() && expiry.get().before(new Date()))) {
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        RequestEntity<?> request = RequestEntity.get(aapUri).header(HttpHeaders.AUTHORIZATION, authHeader).build();
        ResponseEntity<String> response = restOperations.exchange(request, String.class);
        jwt = Optional.of(response.getBody());
        try {
            DecodedJWT decodedJwt = JWT.decode(jwt.get());
            expiry = Optional.of(decodedJwt.getExpiresAt());
        } catch (JWTDecodeException e) {
            // Invalid token
            throw new RuntimeException(e);
        }
        log.info("jwt = " + jwt);
    }
    return jwt.get();
}
Also used : JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 35 with JWT

use of com.auth0.android.jwt.JWT in project restheart by SoftInstigate.

the class JwtAuthenticationMechanism method authenticate.

@Override
public AuthenticationMechanism.AuthenticationMechanismOutcome authenticate(HttpServerExchange hse, SecurityContext sc) {
    try {
        String token = getToken(hse);
        if (token != null) {
            if (base64Encoded) {
                token = StringUtils.newStringUtf8(Base64.getUrlDecoder().decode(token));
            }
            DecodedJWT verifiedJwt = jwtVerifier.verify(token);
            String subject = verifiedJwt.getClaim(usernameClaim).asString();
            if (subject == null) {
                LOGGER.debug("username not specified with claim {}", usernameClaim);
                sc.authenticationFailed("JwtAuthenticationManager", "username not specified");
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
            Set<String> actualRoles = new LinkedHashSet<>();
            if (rolesClaim != null) {
                Claim _roles = verifiedJwt.getClaim(rolesClaim);
                if (_roles != null && !_roles.isNull()) {
                    try {
                        String[] __roles = _roles.asArray(String.class);
                        if (__roles != null) {
                            for (String role : __roles) {
                                actualRoles.add(role);
                            }
                        } else {
                            LOGGER.debug("roles is not an array: {}", _roles.asString());
                            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
                        }
                    } catch (JWTDecodeException ex) {
                        LOGGER.warn("Jwt cannot get roles from claim {}, " + "extepected an array of strings: {}", rolesClaim, _roles.toString());
                    }
                }
            } else if (this.fixedRoles != null) {
                actualRoles.addAll(this.fixedRoles);
            }
            if (this.extraJwtVerifier != null) {
                this.extraJwtVerifier.accept(verifiedJwt);
            }
            var jwtPayload = new String(Base64.getUrlDecoder().decode(verifiedJwt.getPayload()), Charset.forName("UTF-8"));
            JwtAccount account = new JwtAccount(subject, actualRoles, jwtPayload);
            sc.authenticationComplete(account, "JwtAuthenticationManager", false);
            Request.of(hse).addXForwardedHeader("Jwt-Payload", jwtPayload);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        }
    } catch (JWTVerificationException ex) {
        LOGGER.debug("Jwt not verified: {}", ex.getMessage());
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) JwtAccount(org.restheart.security.JwtAccount) 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