MSAL用于DNS和记录的Java Web API

yvt65v4c  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(148)

我们如何使用Azure Web服务API在Azure服务器上创建区域DNS和记录?最新的“MSAL”库不是基于ADAL的?但是DNS库支持https://github.com/Azure-Samples/dns-java-host-and-manage-your-domains没有提到使用MSAL访问令牌的任何方式。例如

ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(client, tenant, key, AzureEnvironment.AZURE);
azure = Azure.authenticate(credentials).withSubscription(subscriptionId);
ResourceGroup resourceGroup = azure.resourceGroups().define(rgName)
        .withRegion(Region.US_EAST2)
        .create();

System.out.println("Creating root DNS zone " + customDomainName + "...");
DnsZone rootDnsZone = azure.dnsZones().define(customDomainName)
        .withExistingResourceGroup(resourceGroup)
        .create();

但是它使用的是密钥而不是MSAL提供的访问令牌。这可以通过Azure内部使用ADAL的旧方式来实现。

b09cbbtk

b09cbbtk1#

如果您想使用Azure java管理SDK管理带有AD访问令牌的Azure DNS,请参考以下代码
a.创建一个服务主体(我使用Azure CLI来执行此操作)

az login
az account set --subscription "<your subscription id>"
# the sp will have Azure Contributor role
az ad sp create-for-rbac -n "readMetric"

1.代码

public void test() throws MalformedURLException, ExecutionException, InterruptedException {


        AzureTokenCredentials tokenCredentials = new AzureTokenCredentials(AzureEnvironment.AZURE,ADProperty.tenantId) {
            @Override
            public String getToken(String resource) throws IOException {
                String token =null;
                // use msal to get Azure AD access token
                ConfidentialClientApplication app = ConfidentialClientApplication.builder(
                        ADProperty.clientId,  // sp appid
                        ClientCredentialFactory.createFromSecret(ADProperty.clientKey)) // sp password
                        .authority(ADProperty.authority) // "https://login.microsoftonline.com/" + sp tenant id
                        .build();
                ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                        Collections.singleton("https://management.azure.com/.default"))
                        .build();
                CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
                try {
                    token =future.get().accessToken();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                return  token;
            }
        };

        Azure azure = Azure.authenticate(tokenCredentials)
                .withSubscription(ADProperty.subscriptionId); // sp subscription id
        DnsZone rootDnsZone = azure.dnsZones().define("mydevchat.com")
                .withExistingResourceGroup("jimtest")
                .create();
        System.out.println("create DNSZone " + rootDnsZone.name() + " successfully");
}

相关问题