BartAlpha
BartAlpha

Reputation: 21

Validation of Azure AD token signature is invalid. The Token's Signature resulted invalid when verified using the Algorithm: SHA256withRSA

I have a problem regarding the validation of an azure active directory token. I receive the token using my application_id and the username and password of a user. I'll then validate it but it results in an invalid signature. The code fragment for the validation is as follows:

    // Request access token from AAD
    IAuthenticationResult result = getAccessToken(userName, password);
    String auth = result.accessToken();
    DecodedJWT jwt = JWT.decode(auth);
    JwkProvider provider = null;
    Jwk jwk = null;
    Algorithm algo = null;
    try {
        provider = new UrlJwkProvider(new URL("https://login.microsoftonline.com/common/discovery/keys"));
        jwk = provider.get(jwt.getKeyId());
        System.out.println(jwk.getPublicKey());
        algo = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
        algo.verify(jwt);
    }  catch (SignatureVerificationException e) {

        System.out.println(e.getMessage());

    } catch (JwkException e) {
        e.printStackTrace();
    }

I retrieve the token information with this method

private static IAuthenticationResult getAccessToken(String userName, String password)
        throws MalformedURLException, InterruptedException, ExecutionException {

    PublicClientApplication pca = PublicClientApplication.builder(
            APP_ID).
            authority(AUTHORITY).build();

    String scopes = "User.Read";
    UserNamePasswordParameters parameters = UserNamePasswordParameters.builder(
            Collections.singleton(scopes),
            userName,
            password.toCharArray()).build();
    IAuthenticationResult result = pca.acquireToken(parameters).get();
    return result;
}

The program always end up catching the SignatureVerificationException. I tried validating the token manually with the jwt.io, where I paste the certificate that I get when i compare the kid claim with the one on https://login.microsoftonline.com/common/discovery/keys but I also get Invalid Signature as a result. Is there something wrong with my token because the validating processes both say the signature is invalid in jwt.io and in my java program or is there another way to validate Azure AD tokens?

EDIT: The solution was changing the scope from "User.Read" to "[client_id]/.default".

Upvotes: 2

Views: 2535

Answers (1)

Carl Zhao
Carl Zhao

Reputation: 9519

Because you are getting the token of the custom api, not the token of the ms graph api. So you need to set the scope to: {api app client_id}/.default

Upvotes: 4

Related Questions