Search in sources :

Example 26 with JWT

use of com.auth0.android.jwt.JWT in project cumulocity-lora by SoftwareAG.

the class JwtInterceptor method intercept.

@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    DecodedJWT decodedJwt = null;
    if (jwt != null) {
        try {
            decodedJwt = JWT.decode(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Couldn't parse JWT", e);
        }
    }
    if (decodedJwt == null || decodedJwt.getExpiresAt().before(Calendar.getInstance().getTime())) {
        jwt = getToken();
    }
    request = request.newBuilder().header("Authorization", "Bearer " + jwt).header("Content-Type", MediaType.APPLICATION_JSON_VALUE).header("Accept", MediaType.APPLICATION_JSON_VALUE).build();
    okhttp3.Response response = chain.proceed(request);
    if (!response.isSuccessful()) {
        logger.error("Error message from Thingpark: {}", response.body().string());
        logger.error("Request was: {}", request);
        if (response.code() == 500) {
            logger.error("Error 500 detected. Thingpark is unstable, we'll retry up to 5 times just in case...");
            int cpt = 0;
            while (!response.isSuccessful() && cpt < 5) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                response = chain.proceed(request);
                cpt++;
            }
            if (!response.isSuccessful()) {
                logger.error("We were unable to reach ThingPark after 5 tries, please contact Actility support.");
            }
        }
    }
    if (!response.isSuccessful()) {
        logger.error("Full error is: {}", response.body().string());
    }
    logger.info("Response code from {} {}: {}", request.method(), request.url(), response.code());
    return response;
}
Also used : Request(okhttp3.Request) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IOException(java.io.IOException)

Example 27 with JWT

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

the class JWTSigningFunctions method createJWTToken.

/**
 * Creates and returns a JWT string
 *
 * @param main
 * @param algorithm   The signing algorithm to use when creating the token. Refer to
 *                    {@link JWTSigningKey.SupportedAlgorithms}
 * @param payload     JSON object containing user defined claims to be added to the JWT payload
 * @param jwksDomain  Used as the issuer in the JWT payload
 * @param jwtValidity Used to set iat anf exp claims in the JWT payload
 * @return String token
 * @throws StorageQueryException                   If there is an error interacting with the database
 * @throws StorageTransactionLogicException        If there is an error interacting with the database
 * @throws NoSuchAlgorithmException                If there is an error when using Java's cryptography packages
 * @throws InvalidKeySpecException                 If there is an error when using Java's cryptography packages
 * @throws JWTCreationException                    If there is an error when creating JWTs
 * @throws UnsupportedJWTSigningAlgorithmException If the algorithm provided does not match any of the supported
 *                                                 algorithms
 */
@SuppressWarnings("unchecked")
public static String createJWTToken(Main main, String algorithm, JsonObject payload, String jwksDomain, long jwtValidity) throws StorageQueryException, StorageTransactionLogicException, NoSuchAlgorithmException, InvalidKeySpecException, JWTCreationException, UnsupportedJWTSigningAlgorithmException {
    // TODO: In the future we will have a way for the user to send a custom key id to use
    JWTSigningKey.SupportedAlgorithms supportedAlgorithm;
    try {
        supportedAlgorithm = JWTSigningKey.SupportedAlgorithms.valueOf(algorithm);
    } catch (IllegalArgumentException e) {
        // If it enters this block then the string value provided does not match the algorithms we support
        throw new UnsupportedJWTSigningAlgorithmException();
    }
    JWTSigningKeyInfo keyToUse = JWTSigningKey.getInstance(main).getOrCreateAndGetKeyForAlgorithm(supportedAlgorithm);
    // Get an instance of auth0's Algorithm which is needed when signing using auth0's package
    Algorithm signingAlgorithm = getAuth0Algorithm(supportedAlgorithm, keyToUse);
    // Create the claims for the JWT header
    Map<String, Object> headerClaims = new HashMap<>();
    // All examples in the RFC have the algorithm
    headerClaims.put("alg", supportedAlgorithm.name().toUpperCase());
    // in upper case
    headerClaims.put("typ", "JWT");
    headerClaims.put("kid", keyToUse.keyId);
    long currentTimeInMillis = System.currentTimeMillis();
    // JWT Expiry is seconds from epoch not millis
    long jwtExpiry = Double.valueOf(Math.ceil((currentTimeInMillis / 1000.0))).longValue() + (jwtValidity);
    // Add relevant claims to the payload, note we only add/override ones that we absolutely need to.
    Map<String, Object> jwtPayload = new Gson().fromJson(payload, HashMap.class);
    jwtPayload.putIfAbsent("iss", jwksDomain);
    jwtPayload.put("exp", jwtExpiry);
    // JWT uses seconds from epoch not millis
    jwtPayload.put("iat", currentTimeInMillis / 1000);
    return com.auth0.jwt.JWT.create().withPayload(jwtPayload).withHeader(headerClaims).sign(signingAlgorithm);
}
Also used : UnsupportedJWTSigningAlgorithmException(io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException) JWTSigningKeyInfo(io.supertokens.pluginInterface.jwt.JWTSigningKeyInfo) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 28 with JWT

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

the class JWKSTest method testThatJWKListContainsValidKeyForCreatedJWT.

/**
 * Test that JWK list contains a key with the same id as the kid in the JWT header
 */
@Test
public void testThatJWKListContainsValidKeyForCreatedJWT() throws Exception {
    String[] args = { "../" };
    TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));
    String algorithm = "RS256";
    JsonObject payload = new JsonObject();
    payload.addProperty("customClaim", "customValue");
    String jwksDomain = "http://localhost";
    long validity = 3600;
    String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity);
    DecodedJWT decodedJWT = JWT.decode(jwt);
    String headerKeyId = decodedJWT.getHeaderClaim("kid").asString();
    boolean didFindKey = false;
    List<JsonObject> keysFromStorage = JWTSigningFunctions.getJWKS(process.getProcess());
    for (int i = 0; i < keysFromStorage.size(); i++) {
        JsonObject key = keysFromStorage.get(i);
        if (key.get("kid").getAsString().equals(headerKeyId) && key.get("kty").getAsString().equalsIgnoreCase("rsa") && key.get("alg").getAsString().equalsIgnoreCase("rs256")) {
            didFindKey = true;
            break;
        }
    }
    assert didFindKey;
    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) Test(org.junit.Test)

Example 29 with JWT

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

the class JWTCreateTest method testThatDecodedJWTUsesCustomIssuer.

/**
 * Test that final JWT uses custom iss claim instead of jwks domain
 */
@Test
public void testThatDecodedJWTUsesCustomIssuer() throws Exception {
    String[] args = { "../" };
    TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));
    String algorithm = "RS256";
    JsonObject payload = new JsonObject();
    payload.addProperty("iss", "http://customiss");
    String jwksDomain = "http://localhost";
    long validity = 3600;
    String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity);
    DecodedJWT decodedJWT = JWT.decode(jwt);
    String issuer = decodedJWT.getIssuer();
    if (!issuer.equals("http://customiss")) {
        throw new Exception("Decoded JWT does not contain 'iss' claim matching user defined value");
    }
    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) UnsupportedJWTSigningAlgorithmException(io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException) Test(org.junit.Test)

Example 30 with JWT

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

the class JWTCreateTest method testThatDecodedJWTHasAValidHeader.

/**
 * Verify that the JWT header has the required properties and that the values are valid
 */
@Test
public void testThatDecodedJWTHasAValidHeader() throws Exception {
    String[] args = { "../" };
    TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));
    String algorithm = "RS256";
    JsonObject payload = new JsonObject();
    payload.addProperty("customClaim", "customValue");
    String jwksDomain = "http://localhost";
    long validity = 3600;
    String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity);
    DecodedJWT decodedJWT = JWT.decode(jwt);
    Claim headerAlg = decodedJWT.getHeaderClaim("alg");
    Claim headerType = decodedJWT.getHeaderClaim("typ");
    Claim headerKeyId = decodedJWT.getHeaderClaim("kid");
    if (headerAlg.isNull() || headerType.isNull() || headerKeyId.isNull()) {
        throw new Exception("JWT header is missing one or more required claim (alg, typ, kid)");
    }
    if (!headerAlg.asString().equals(algorithm)) {
        throw new Exception("Algorithm in JWT header does not match algorithm passed to JWTSigningFunctions.createJWTToken");
    }
    if (!headerType.asString().equals("JWT")) {
        throw new Exception("JWT header contains wrong type: Expected: JWT, Actual: " + headerType.asString());
    }
    if (headerKeyId.asString().isEmpty()) {
        throw new Exception("Value for kid in JWT header is invalid");
    }
    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) UnsupportedJWTSigningAlgorithmException(io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException) Test(org.junit.Test)

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