【问题标题】:How to use msal4j to authenticate with a token?如何使用 msal4j 使用令牌进行身份验证?
【发布时间】:2020-04-24 09:32:19
【问题描述】:

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

在此先感谢

胡安·安东尼奥

【问题讨论】:

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


    【解决方案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

    胡安·安东尼奥

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2017-06-05
      • 2014-09-26
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2011-11-13
      相关资源
      最近更新 更多