使用 azure java sdk 对 Azure 进行身份验证

Authentication of Azure using azure java sdk

这是检查客户端、租户、密钥是否有效的正确方法吗? 那么这段代码需要什么jar,在哪里下载呢?

String client = "xxxxxxxxxxx";
String tenant = "xxxxxxxxxxx";
String key = "xxxxxxxxxxx";
String subscriptionId = "xxxxxxxxxxx";

ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(client, tenant,key, AzureEnvironment.AZURE);
Azure azure = Azure.configure().authenticate(credentials).withDefaultSubscription();
azure.subscriptions().list();

如果您想获取访问令牌,可以尝试下面的code

private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {

        ConfidentialClientApplication app = ConfidentialClientApplication.builder(
                CONFIDENTIAL_CLIENT_ID,
                ClientCredentialFactory.createFromSecret(CONFIDENTIAL_CLIENT_SECRET))
                .authority(TENANT_SPECIFIC_AUTHORITY)
                .build();

        // With client credentials flows the scope is ALWAYS of the shape "resource/.default", as the
        // application permissions need to be set statically (in the portal), and then granted by a tenant administrator
        ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                Collections.singleton(GRAPH_DEFAULT_SCOPE))
                .build();

        CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
        return future.get();
    }

依赖在pom.xml这样,或者下载jarhere:

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>msal4j</artifactId>
        <version>1.2.0</version>
    </dependency>

有关详细信息,请参阅 sample


401错误与您的权限有关。 Get subscriptions 需要范围 https://management.azure.com/.default.