{
"AzureAd": {
// Same AzureAd section as before.
},
"MyWebApi": {
"BaseUrl": "https://localhost:44372/",
"RelativePath": "api/TodoList",
"RequestAppToken": true,
"Scopes": [ "[Enter here the scopes for your web API]" ]
}
}
final static String GRAPH_DEFAULT_SCOPE = "https://microsoftgraph.chinacloudapi.cn/.default";
使用 Microsoft.Identity.Web 时,无需获取令牌。 可以使用更高级别的 API,如从守护程序应用程序调用一个 Web API中所示。 但是,如果使用的 SDK 需要令牌,以下代码片段则会显示如何获取此令牌。
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
// In the Program.cs, acquire a token for your downstream API
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
ITokenAcquirer acquirer = tokenAcquirerFactory.GetTokenAcquirer();
AcquireTokenResult tokenResult = await acquirer.GetTokenForUserAsync(new[] { "https://microsoftgraph.chinacloudapi.cn/.default" });
string accessToken = tokenResult.AccessToken;
private static IAuthenticationResult acquireToken() throws Exception {
// Load token cache from file and initialize token cache aspect. The token cache will have
// dummy data, so the acquireTokenSilently call will fail.
TokenCacheAspect tokenCacheAspect = new TokenCacheAspect("sample_cache.json");
IClientCredential credential = ClientCredentialFactory.createFromSecret(CLIENT_SECRET);
ConfidentialClientApplication cca =
ConfidentialClientApplication
.builder(CLIENT_ID, credential)
.authority(AUTHORITY)
.setTokenCacheAccessAspect(tokenCacheAspect)
.build();
IAuthenticationResult result;
try {
SilentParameters silentParameters =
SilentParameters
.builder(SCOPE)
.build();
// try to acquire token silently. This call will fail since the token cache does not
// have a token for the application you are requesting an access token for
result = cca.acquireTokenSilently(silentParameters).join();
} catch (Exception ex) {
if (ex.getCause() instanceof MsalException) {
ClientCredentialParameters parameters =
ClientCredentialParameters
.builder(SCOPE)
.build();
// Try to acquire a token. If successful, you should see
// the token information printed out to console
result = cca.acquireToken(parameters).join();
} else {
// Handle other exceptions accordingly
throw ex;
}
}
return result;
}
# The pattern to acquire a token looks like this.
result = None
# First, the code looks up a token from the cache.
# Because we're looking for a token for the current app, not for a user,
# use None for the account parameter.
result = app.acquire_token_silent(config["scope"], account=None)
if not result:
logging.info("No suitable token exists in cache. Let's get a new one from Azure AD.")
result = app.acquire_token_for_client(scopes=config["scope"])
if "access_token" in result:
# Call a protected API with the access token.
print(result["token_type"])
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id")) # You might need this when reporting a bug.
using Microsoft.Identity.Client;
// With client credentials flows, the scope is always of the shape "resource/.default" because the
// application permissions need to be set statically (in the portal or by PowerShell), and then granted by
// a tenant administrator.
string[] scopes = new string[] { "https://microsoftgraph.chinacloudapi.cn/.default" };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// The application doesn't have sufficient permissions.
// - Did you declare enough app permissions during app creation?
// - Did the tenant admin grant permissions to the application?
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
// Invalid scope. The scope has to be in the form "https://resourceurl/.default"
// Mitigation: Change the scope to be as expected.
}