Search in sources :

Example 21 with Algorithm

use of com.auth0.jwt.Algorithm in project java-jwt by auth0.

the class ECDSABouncyCastleProviderTests method shouldPassECDSA256KVerificationWithProvidedPublicKey.

@Test
public void shouldPassECDSA256KVerificationWithProvidedPublicKey() throws Exception {
    ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
    PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_256K, "EC");
    when(provider.getPublicKeyById("my-key-id")).thenReturn((ECPublicKey) publicKey);
    Algorithm algorithm = Algorithm.ECDSA256K(provider);
    algorithm.verify(JWT.decode(ES256K_JWT));
}
Also used : ECDSAKeyProvider(com.auth0.jwt.interfaces.ECDSAKeyProvider) ECPublicKey(java.security.interfaces.ECPublicKey) ECDSAAlgorithmTest(com.auth0.jwt.algorithms.ECDSAAlgorithmTest) Test(org.junit.Test)

Example 22 with Algorithm

use of com.auth0.jwt.Algorithm in project java-jwt by auth0.

the class ECDSABouncyCastleProviderTests method shouldFailECDSA256KVerificationWhenProvidedPublicKeyIsNull.

@Test
public void shouldFailECDSA256KVerificationWhenProvidedPublicKeyIsNull() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA");
    exception.expectCause(isA(IllegalStateException.class));
    exception.expectCause(hasMessage(is("The given Public Key is null.")));
    ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
    when(provider.getPublicKeyById("my-key-id")).thenReturn(null);
    Algorithm algorithm = Algorithm.ECDSA256K(provider);
    algorithm.verify(JWT.decode(ES256K_JWT));
}
Also used : ECDSAKeyProvider(com.auth0.jwt.interfaces.ECDSAKeyProvider) ECDSAAlgorithmTest(com.auth0.jwt.algorithms.ECDSAAlgorithmTest) Test(org.junit.Test)

Example 23 with Algorithm

use of com.auth0.jwt.Algorithm in project mapsmessaging_server by Maps-Messaging.

the class AwsJwtLoginModule method login.

@Override
public boolean login() throws LoginException {
    // prompt for a user name and password
    if (callbackHandler == null) {
        throw new LoginException("Error: no CallbackHandler available to garner authentication information from the user");
    }
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("user name: ");
    callbacks[1] = new PasswordCallback("password: ", false);
    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        if (tmpPassword == null) {
            tmpPassword = new char[0];
        }
        String token = new String(tmpPassword);
        ((PasswordCallback) callbacks[1]).clearPassword();
        // Password should be a valid JWT
        RSAKeyProvider keyProvider = new AwsCognitoRSAKeyProvider(region, poolId);
        Algorithm algorithm = Algorithm.RSA256(keyProvider);
        JWTVerifier jwtVerifier = JWT.require(algorithm).withAudience(clientId).build();
        jwtVerifier.verify(token);
        return true;
    } catch (IOException ioe) {
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user");
    }
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) IOException(java.io.IOException) Algorithm(com.auth0.jwt.algorithms.Algorithm) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginException(javax.security.auth.login.LoginException) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 24 with Algorithm

use of com.auth0.jwt.Algorithm 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 25 with Algorithm

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

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)206 Test (org.junit.Test)160 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)90 JWTVerifier (com.auth0.jwt.JWTVerifier)79 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)79 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)61 Date (java.util.Date)57 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)51 RSAPublicKey (java.security.interfaces.RSAPublicKey)36 ECPublicKey (java.security.interfaces.ECPublicKey)34 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)31 IOException (java.io.IOException)30 JWTCreator (com.auth0.jwt.JWTCreator)28 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)25 ECPrivateKey (java.security.interfaces.ECPrivateKey)23 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 HashMap (java.util.HashMap)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 JsonObject (com.google.gson.JsonObject)15