admin管理员组文章数量:1122846
The client FE app (Blazor WASM) signs in the user and then passes the access token along to the server BE app (ASP.NET Core Web API). Now, I'd like to somehow add the Graph client to the DI container in the server app and make calls to Graph API from services and controllers there. How do I do that?
Client app configuration
Client - 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<AuthorizationMessageHandler>()
.ConfigureHandler(
authorizedUrls: [ appSettings.ServerApi.Url ],
scopes: [ appSettings.ServerApi.AccessScope ]
));
Client - appsettings.json
"AzureAd": {
"Authentication": {
"Authority": ";,
"ClientId": "client-id-here"
},
"DefaultAccessTokenScopes": [
"api://server-app-id-here/API.Access",
".Read"
]
}
Server app configuration
Server - Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApis:MicrosoftGraph"))
.AddInMemoryTokenCaches();
Server - appsettings.json
"AzureAd": {
"Instance": "/",
"Domain": "myusername.onmicrosoft",
"TenantId": "my-tenant-id",
"ClientId": "server-app-client-id",
"ClientSecret": "server-app-secret",
"Scopes": "API.Access",
"CallbackPath": "/signin-oidc"
},
"DownstreamApis": {
"MicrosoftGraph": {
"BaseUrl": ".0",
"Scopes": "User.Read"
}
},
Server - Calling Graph
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<IActionResult> GraphTest()
{
var user = await _graphClient.Me.GetAsync();
return Ok();
}
}
Azure setup
Client app registration
API Permissions:
- MyServerApp: API.Access, Type: Delegated, Status: Granted
- Microsoft Graph: User.Read, Type: Delegated, Status: Granted
Server app registration
Expose an API:
- Scopes: api://my-server-app-id-here/API.Access
- Authorized client applications: my-client-app-id-here
The problem
If I remove the ".Read"
scope to DefaultAccessTokenScopes
in the client's appsettings.json
file I get this error when trying to call 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 .
---> 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.
I tried following the link the error provides for "managing incremental consent" and getting the token in the TestController
through ITokenAcquisition
but that seemingly tries to get the token from Azure. That doesn't seem correct for this scenario (and it doesn't work) -- I already have the access token in the Request.Headers.Authorization
property. The question is how I use it with the GraphServiceClient...
If I keep the User.Read
scope in the DefaultAccessTokenScopes
this is the error I get:
Request URL: .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 .Read openid profile offline_access is not valid.
The client FE app (Blazor WASM) signs in the user and then passes the access token along to the server BE app (ASP.NET Core Web API). Now, I'd like to somehow add the Graph client to the DI container in the server app and make calls to Graph API from services and controllers there. How do I do that?
Client app configuration
Client - 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<AuthorizationMessageHandler>()
.ConfigureHandler(
authorizedUrls: [ appSettings.ServerApi.Url ],
scopes: [ appSettings.ServerApi.AccessScope ]
));
Client - 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"
]
}
Server app configuration
Server - Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApis:MicrosoftGraph"))
.AddInMemoryTokenCaches();
Server - 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"
}
},
Server - Calling Graph
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<IActionResult> GraphTest()
{
var user = await _graphClient.Me.GetAsync();
return Ok();
}
}
Azure setup
Client app registration
API Permissions:
- MyServerApp: API.Access, Type: Delegated, Status: Granted
- Microsoft Graph: User.Read, Type: Delegated, Status: Granted
Server app registration
Expose an API:
- Scopes: api://my-server-app-id-here/API.Access
- Authorized client applications: my-client-app-id-here
The problem
If I remove the "https://graph.microsoft.com/User.Read"
scope to DefaultAccessTokenScopes
in the client's appsettings.json
file I get this error when trying to call 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.
I tried following the link the error provides for "managing incremental consent" and getting the token in the TestController
through ITokenAcquisition
but that seemingly tries to get the token from Azure. That doesn't seem correct for this scenario (and it doesn't work) -- I already have the access token in the Request.Headers.Authorization
property. The question is how I use it with the GraphServiceClient...
If I keep the User.Read
scope in the DefaultAccessTokenScopes
this is the error I get:
Request URL: https://login.microsoftonline.com/my-tentant-id-here/oauth2/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.
Share
Improve this question
asked Nov 21, 2024 at 12:44
kglundgrenkglundgren
355 bronze badges
3
|
1 Answer
Reset to default 0Note that: You cannot pass two or more resources as scope to generate the token or in the request.
For sample, I tried to generate the token and passed scope as API and the Microsoft Graph API:
GET https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id: ClientID
grant_type: authorization_code
scope: api://xxx/ScopeName https://graph.microsoft.com/User.Read openid profile offline_access
redirect_uri: RedirectURL
code: code
client_secret: Secret
And got the same error:
The error "AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope api://xxx/claims.read https://graph.microsoft.com/User.Read openid profile offline_access is not valid." usually occurs if you are passing two or more distinct resources as scope in the request.
- One access token can contain only one aud , in your case one single token cannot call the API and the Microsoft Graph.
- The aud claim in an access token is designated for the specific API or resource for which the token is created.
Hence to resolve the error, you need to make two different requests one to call the API and one more to call the Microsoft Graph API:
To call the API pass scope as api://xxx/ScopeName
:
To call Microsoft Graph API, pass scope as https://graph.microsoft.com/User.Read openid profile offline_access
:
本文标签:
版权声明:本文标题:c# - How do I call MS Graph API from the server app in a Blazor WASM Hosted solution, using the Access Token from the client app 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736310841a1934520.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
[Authorize]
attribute beforepublic class TestController : ControllerBase{
? You are working on on-behalf-of flow now, and your codes looks good except the scopes just like what Rukmini said. But you already put"api://server-app-id-here/API.Access"
before Graph API scope, so that the token should work as well. May I know, whether your access token could work when you create an API with[Authorize]
attribute on the Controller and use the token to call that API? If not, I'm afraid there's some mistake in configuration. – Tiny Wang Commented Nov 22, 2024 at 10:41builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration).EnableTokenAcquisitionToCallDownstreamApi().AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApis:MicrosoftGraph")).AddInMemoryTokenCaches();
so that whenever you are using the access token to call a secured API successfully, in that API GraphClient is authorized...My humble opinion. – Tiny Wang Commented Nov 22, 2024 at 10:47