Конфигурация клиентского приложения
Клиент — Program.cs
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions);
});
builder.Services
.AddHttpClient(HttpClients.SERVER_API, client =>
{
client.BaseAddress = new Uri(appSettings.ServerApi.Url);
})
// This configues the client to add the JWT to the 'Authorization' header
// for every request made to the authorized URLs.
.AddHttpMessageHandler(sp =>
sp.GetRequiredService()
.ConfigureHandler(
authorizedUrls: [ appSettings.ServerApi.Url ],
scopes: [ appSettings.ServerApi.AccessScope ]
));
Клиент — appsettings.json
"AzureAd": {
"Authentication": {
"Authority": "https://login.microsoftonline.com/my-authority-here",
"ClientId": "client-id-here"
},
"DefaultAccessTokenScopes": [
"api://server-app-id-here/API.Access",
"https://graph.microsoft.com/User.Read"
]
}
Конфигурация серверного приложения
Сервер — Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApis:MicrosoftGraph"))
.AddInMemoryTokenCaches();
Сервер — appsettings.json
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "myusername.onmicrosoft.com",
"TenantId": "my-tenant-id",
"ClientId": "server-app-client-id",
"ClientSecret": "server-app-secret",
"Scopes": "API.Access",
"CallbackPath": "/signin-oidc"
},
"DownstreamApis": {
"MicrosoftGraph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "User.Read"
}
},
Сервер — граф вызовов
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
using Microsoft.Identity.Web;
namespace ChatPortal.Server.Controllers;
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly GraphServiceClient _graphClient;
public TestController(GraphServiceClient graphClient)
{
_graphClient = graphClient;
}
[HttpGet("graph")]
public async Task GraphTest()
{
var user = await _graphClient.Me.GetAsync();
return Ok();
}
}
Настройка Azure
Регистрация клиентского приложения
Разрешения API:
- MyServerApp: API.Access, тип: делегирован, статус: предоставлен
- Microsoft Graph: User.Read, тип: делегирован , Статус: Разрешено
Откройте API:
- Области применения: api://my-server-app-id-here/API.Access
Авторизованные клиентские приложения: my-client-app-id-here< /li>
Если я удалю область «https://graph.microsoft.com/User.Read» в DefaultAccessTokenScopes в клиентском appsettings.json я получаю эту ошибку при попытке вызвать Graph:
[12:47:58 ERR] An unhandled exception has occurred while executing the request.
Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException: IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent.
---> MSAL.NetCore.4.66.1.0.MsalUiRequiredException:
ErrorCode: invalid_grant
Microsoft.Identity.Client.MsalUiRequiredException: AADSTS65001: The user or administrator has not consented to use the application with ID 'my-id-here' named 'ChatPortal.Server'. Send an interactive authorization request for this user and resource.
Я попробовал перейти по ссылке, которую предоставляет ошибка, для «управления дополнительным согласием» и получения токена в TestController через ITokenAcquisition, но, по-видимому, он пытается получить токен из Лазурного. Это кажется неправильным для этого сценария (и это не работает) — у меня уже есть токен доступа в свойстве Request.Headers.Authorization. Вопрос в том, как я использую его с GraphServiceClient...
Если я сохраняю область User.Read в DefaultAccessTokenScopes, я получаю следующую ошибку:
Request URL: https://login.microsoftonline.com/my-te ... v2.0/token
Invalid request: AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope api://server-app-id-here/API.Access https://graph.microsoft.com/User.Read openid profile offline_access is not valid.
Подробнее здесь: https://stackoverflow.com/questions/792 ... d-solution