How to mock JWKS RSA Algorithm , validate signature and test roles using junit or mockito in Java for below method microsoftJwksUrl is an AzureActiveDirectory endpoint .
Below is the method which need to mock:
How to mock JWKS RSA Algorithm , validate signature and test roles using junit or mockito in Java for below method microsoftJwksUrl for an AzureActiveDirectory endpoint
public String[] getAadRoles(String token, String intendedAudience, String microsoftJwksUrl)
throws AadTokenAuthenticationFailedException {
//Decode AAD token
DecodedJWT jwt = JWT.decode(token);
//Get Provider from the endpoint :
//microsoftJwksUrl=https://login.microsoftonline.com/common/discovery/v2.0/keys
JwkProvider provider = new UrlJwkProvider(new URL(microsoftJwksUrl));
Jwk jwk = provider.get(jwt.getKeyId());
Algorithm algorithm=Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
//Verify Algorithm
algorithm.verify(jwt);
String audience = jwt.getAudience().get(0);
Date expiresAt = jwt.getExpiresAt();
Date currentDateTime = new Date();
Claim roles = jwt.getClaim("roles");
//checks if it's audience is correct and token is valid
if (audience.contentEquals(intendedAudience) && currentDateTime.before(expiresAt)) {
return roles!=null ? roles.asArray(String.class) : new String[] {};
} else {
String errorMessage = String.format("Token not valid for Audience {%s} "
+ ", with Expiry Time as {%s}.", audience,
expiresAt.toString());
LOG.error(errorMessage);
throw new AadTokenAuthenticationFailedException();
}
}