是否可以通过 azure graph 获取访问令牌并使用它来访问 azure 存储帐户?

Is it possible to get access token through azure graph and use it to access azure storage accounts?

例如,我可以通过图 api 通过 getaccesstokencredentials(username, password) 进行身份验证 我可以使用此令牌访问 Azure 吗? 目前我们可以使用管理库中的 usertokencredentials 和 applicationtokencredentials,完成后您可以创建 azure class 实例。 Azure azure = Azure.authenticate(credentials).withdefaultsubscription。 我想知道我们是否可以使用来自 getaccesstokencredentials 的令牌而不是 usertokentcredentials 和 applicationtokencredentials

我们不能使用相同的访问令牌来调用图 api 和调用 api 来管理 Azure 资源。因为图 api 的资源 url 是 https://graph.microsoft.com/ 但 Azure 管理 rest api 的资源 url 是 https://management.azure.com/。详情请参考https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-api-authentication.

另外,关于如何使用Azure AD访问Azure存储,请参考以下步骤:

  1. 为您的委托人添加角色分配。

  1. 获取令牌。

    public static String getToken() throws Exception {
        String TENANT_ID = "your tenant id or name, e4c9*-*-*-*-*57fb";
        String AUTHORITY = "https://login.microsoftonline.com/" + TENANT_ID;
        String CLIENT_ID = "your application id, dc17*-*-*-*a5e7";
        String CLIENT_SECRET = "the secret, /pG*32";
        String RESOURCE = "https://storage.azure.com/";
        String ACCESS_TOKEN = null;
        ExecutorService service = Executors.newFixedThreadPool(1);
        AuthenticationContext context = null;
        try {
            context = new AuthenticationContext(AUTHORITY, false, service);
            ClientCredential credential = new ClientCredential(CLIENT_ID, CLIENT_SECRET);
            Future<AuthenticationResult> future = context.acquireToken(RESOURCE, credential, null);
            ACCESS_TOKEN = future.get().getAccessToken();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } finally {
            service.shutdown();
        }
        return ACCESS_TOKEN;
    }
    
  2. 访问 blob。

    public static void main(String[] args) throws Exception {
        String token = getToken();
        StorageCredentialsToken credentialsToken = new StorageCredentialsToken("storagetest789", token);
        CloudBlobClient blobClient = new CloudBlobClient(new URI("https://storagetest789.blob.core.windows.net/"), credentialsToken);
        CloudBlobContainer blobContainer = blobClient.getContainerReference("pub");
        CloudBlockBlob blockBlob = blobContainer.getBlockBlobReference("test1.txt");
        blockBlob.uploadText("mytest");
    }
    

详情请参考https://docs.microsoft.com/en-us/azure/storage/common/storage-auth-aad