{
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 ]
));
< /code>
client-appsettings.json < /h3>
"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"
]
}
< /code>
Конфигурация приложения сервера < /h2>
server-program.cs < /h3>
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApis:MicrosoftGraph"))
.AddInMemoryTokenCaches();
< /code>
server-appsettings.json < /h3>
"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"
}
},
< /code>
Сервер-Вызовов граф < /h3>
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();
}
}
< /code>
Настройка Azure < /h2>
Регистрация приложений клиента < /h3>
api Remissions: < /strong> < /p>
- myserverapp: api.access, type: delegted, status: wreated < /> User.read, тип: делегирован, статус: предоставлено
Регистрация приложений сервера
api:
- /> Авторизованные клиентские приложения: my-client-app-id-here
Если я удалю "https://graph.microsoft.com/user.read" scope to defaultaccesstokenscopes
[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 , но это, казалось бы, пытается получить токен из Azure. Это не кажется правильным для этого сценария (и он не работает) - у меня уже есть токен доступа в запросе. Headers.authorization свойство. Вопрос заключается в том, как я использую его с GraphServiceClient ...
Если я сохраняю пользователь. Читать racope в 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