Search code examples
azureazure-authenticationazure-java-sdk

Authentication of Azure using azure java sdk


Is this the correct way of checking client, tenant,secret key are valid? then what are the jars required to this code and where to download it?

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();

Solution

  • If you want to get access token, you could try the code below.

    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();
        }
    

    The dependency in the pom.xml like this, or dowanload the jar here:

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

    For more details, see the sample.


    401 error is related to your permission. Get subscriptions need scope https://management.azure.com/.default.