如何连接Microsoft Azure Active Directory



我创建了一个springBoot应用程序,并使用GraphApi 连接到Azure Active Directory

例如

https://login.microsoftonline.com/{{tenantId}}/oauth2/v2.0/token

客户端凭据、客户端机密、租户ID

/users
method() {
accesstoken() -->> calling AccessToken graphApi and getting accessToken
user() -->> using above accessToken hitting /getuser graphApi
}
/group
method() {
accesstoken() -->> calling AccessToken graphApi and getting accessToken
user() -->> using above accessToken hitting /getgroup graphApi
}

像这样,我有20种服务方法,请建议实现和共享任何引用URL 的最佳方式

使用acquireTokenSilently方法获取带有MSAL客户端凭据流的访问令牌。

然后使用此令牌调用Microsoft Graph端点。

public static String getUserAccessToken(String[] scopes) {
if (applicationId == null) {
System.out.println("You must initialize Authentication before calling getUserAccessToken");
return null;
}

Set<String> scopeSet = new HashSet<>();

Collections.addAll(scopeSet, scopes);
IClientCredential cred = ClientCredentialFactory.createFromSecret(clientSecret);
ConfidentialClientApplication app;
try {
// Build the MSAL application object for a client credential flow
app = ConfidentialClientApplication.builder(applicationId, cred ).authority(authority).build();
} catch (MalformedURLException e) {
System.out.println("Error creating confidential client: " + e.getMessage());
return null;
}

IAuthenticationResult result;
try{
SilentParameters silentParameters = SilentParameters.builder(scopeSet).build();
result= app.acquireTokenSilently(silentParameters).join();
} catch (Exception ex ){
if (ex.getCause() instanceof MsalException) {

ClientCredentialParameters parameters =
ClientCredentialParameters
.builder(scopeSet)
.build();

// Try to acquire a token. If successful, you should see
// the token information printed out to console
result = app.acquireToken(parameters).join();
} else {
// Handle other exceptions accordingly
System.out.println("Unable to authenticate = " + ex.getMessage());
return null;
}
}
if (result != null) {
// System.out.println("Access Token - " + result.accessToken());
return result.accessToken();
}

return null;
}

此处填写完整的样本。

相关内容

最新更新