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