我正在尝试访问在Azure Active Directory(AAD)中注册的Azure应用。我正在使用OAuth2.O客户端证书协议(https://dev.loganalytics.io/documentation/Authorization/OAuth2)。
使用Rest客户端(邮递员),我可以连接。但是我需要在Java应用程序中做同样的事情。
连接有2个步骤
获取访问令牌。
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
使用访问令牌向工作区发出请求
POST https://api.loganalytics.io/v1/workspaces/8fXXXXX-0a84-XXX-XXX- c1a5XXXXXX/query?timespan=P1D
Authorization: Bearer [access_token]
{
"query": "AzureActivity | limit 10"
}
有人可以帮我写一个Java客户端吗?我提到了以下链接:
但是他们不使用租户ID,并且授予类型不是client_credentials
。
答案 0 :(得分:1)
尝试如下所示的代码模板,使用authResult.getAccessToken()
获取访问令牌,它应该可以工作。
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();
}
有关更多详细信息,请参见此link。