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));
}
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));
}
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");
}
}
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);
}
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));
}
Aggregations