如何使用msal4j进行令牌身份验证?

时间:2020-04-24 09:32:19

标签: azure azure-active-directory azure-java-sdk azure-security

我正在使用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?

非常感谢

胡安·安东尼奥

1 个答案:

答案 0 :(得分:0)

我发现使用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的另一种方式?

胡安·安东尼奥