Как использовать msal4j для аутентификации с помощью токена?

Я использую msal4j, чтобы получить Access Token с пользователем и паролем:

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);

Как только у меня есть токен, предоставленный объектом IAuthenticationResult, я хотел бы проверить токен доступа в будущем вызове.

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

Как это сделать с Java?

Спасибо заранее

Хуан Антонио


person jabrena    schedule 24.04.2020    source источник


Ответы (1)


Я обнаружил, что с помощью Graph API я смог проверить токен.

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

Исходный образец из: https://github.com/Azure-Samples/ms-identity-java-daemon/blob/master/src/main/java/ClientCredentialGrant.java

Есть ли другой способ, только с msal4j?

Хуан Антонио

person jabrena    schedule 24.04.2020