Reputation: 165
I am trying to access my Azure app registered in Azure Active Directory(AAD). I am using the OAuth2.O Client credential protocol (https://dev.loganalytics.io/documentation/Authorization/OAuth2).
Using the Rest client (Postman) I am able to connect. But I need to do the same in my Java application.
There are 2 steps in connection
To get the access-token.
POST https://login.microsoftonline.com/YOUR_AAD_TENANT/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=YOUR_CLIENT_ID
&redirect_uri=YOUR_REDIRECT_URI
&resource=https://management.azure.com/
&client_secret=YOUR_CLIENT_SECRET
To make a request to the workspace using the access token
POST https://api.loganalytics.io/v1/workspaces/8fXXXXX-0a84-XXX-XXX- c1a5XXXXXX/query?timespan=P1D
Authorization: Bearer [access_token]
{
"query": "AzureActivity | limit 10"
}
Can someone help me to write a java client to do above? I referred to the following links:
But they do not use the Tenant id and grant type not client_credentials
.
Upvotes: 0
Views: 1731
Reputation: 42143
Try the code smaple as below, use authResult.getAccessToken()
to get the access token, it should work.
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential; // for service principal
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
// Account specific values
String tenantId = <your tenant id>
String clientId = <your client id>
String password = <your password>
// use adal to Authenticate
AuthenticationContext authContext = null;
AuthenticationResult authResult = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
String url = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
authContext = new AuthenticationContext(url,
false,
service);
ClientCredential clientCred = new ClientCredential(clientId, password);
Future<AuthenticationResult> future = authContext.acquireToken(
"https://management.azure.com/",
clientCred,
null);
authResult = future.get();
} catch (Exception ex) {
// handle exception as needed
} finally {
service.shutdown();
}
For more details, see this link.
Upvotes: 1