1

我正在尝试设置一个本机 Java 应用程序,该应用程序将利用 MS Graph 的 API 在使用 ADAL4j 进行身份验证后访问用户 OneDrive。我正在使用这个库来获取我的访问令牌。到目前为止,我有这个代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.naming.ServiceUnavailableException;

import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;

public class Get {

    private final static String AUTHORITY = "https://login.windows.net/common/oauth2/v2.0/authorize";
    private final static String CLIENT_ID = "29275...011a";
    private final static String RESOURCE = "https://graph.windows.net";


    public static void main(String[] args) throws Exception {

        try (BufferedReader br = new BufferedReader(new InputStreamReader(
            System.in))) {
            System.out.print("Enter username: ");
            String username = br.readLine();
            System.out.print("Enter password: ");
            String password = br.readLine();

            AuthenticationResult result = getAccessTokenFromUserCredentials(
                username, password);
            System.out.println("Access Token - " + result.getAccessToken());
            System.out.println("Refresh Token - " + result.getRefreshToken());
            System.out.println("ID Token - " + result.getIdToken());
            System.out.println("Expires in - " + result.getExpiresAfter());
        }
    }

    private static AuthenticationResult getAccessTokenFromUserCredentials(
        String username, String password) throws Exception {
        AuthenticationContext context = null;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext(AUTHORITY, false, service);
            Future<AuthenticationResult> future = context.acquireToken(RESOURCE, CLIENT_ID, username, password, null);
            result = future.get();
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new ServiceUnavailableException(
                "authentication result was null");
        }
        return result;
    }

}

当我运行它时,我输入帐户凭据,然后打印访问令牌、刷新令牌、ID 令牌和过期时间。然后,我使用 chromes “Advanced Rest Client”插件来测试身份验证令牌(下面的屏幕截图)。

截屏

然后我得到了屏幕截图底部显示的访问令牌验证错误。我不明白令牌不起作用的原因。我在 Azure AD 中注册的应用程序上设置了权限,并且用户已经授予了该应用程序的权限。我唯一能想到的可能是没有指定范围,但我不确定这是问题所在。如果是我如何指定它们?

4

1 回答 1

2

我发现了这个问题。

资源 URI 错误。Azure AD 图形 API 是https://graph.windows.net

Microsoft Graph API 资源 URI 是https://graph.microsoft.com/

于 2017-07-26T17:30:45.203 回答