0

I am using msal4j to get an Access Token with a User & Password:

PublicClientApplication app = PublicClientApplication
        .builder(CLIENT_ID)
        .authority("https://login.microsoftonline.com/organizations")
        .build();

CompletableFuture<IAuthenticationResult> acquireToken = app.acquireToken(
        UserNamePasswordParameters.builder(
                SCOPE, USER_NAME, USER_PASSWORD.toCharArray())
                .build());
IAuthenticationResult authenticationResult = acquireToken.join();
System.out.println(authenticationResult.expiresOnDate());
String accessToken = authenticationResult.accessToken();
String idtoken = authenticationResult.idToken();

System.out.println(accessToken);
System.out.println(idtoken);

Once, I have the token provided by an IAuthenticationResult object, I would like to validate the access token in a future call.

https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens#validating-tokens

How to do it with Java?

Many thanks in advance

Juan Antonio

jabrena
  • 1,166
  • 3
  • 11
  • 25

1 Answers1

0

I found that using Graph API, I was able to use to verify a token.

    private final static String GRAPH_URL = "https://graph.microsoft.com/v1.0/organization";

    private static String getOrganizationDataFromGraph(String accessToken) throws IOException {
        URL url = new URL(GRAPH_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Accept","application/json");

        int httpResponseCode = conn.getResponseCode();
        if(httpResponseCode == HTTPResponse.SC_OK) {

            StringBuilder response;
            try(BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()))){

                String inputLine;
                response = new StringBuilder();
                while (( inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }
            return response.toString();
        } else {
            return String.format("Connection returned HTTP code: %s with message: %s",
                    httpResponseCode, conn.getResponseMessage());
        }
    }

Original sample from: https://github.com/Azure-Samples/ms-identity-java-daemon/blob/master/src/main/java/ClientCredentialGrant.java

Does exist another way, only using msal4j?

Juan Antonio

jabrena
  • 1,166
  • 3
  • 11
  • 25