簡體   English   中英

無法使用來自 Asp.Net 的代表流調用 graphAPI Web API

[英]Unable to call graphAPI using On-behalf-of flow from Asp.Net Web API

我正在嘗試在 Asp.net Web API (.net 5)中實現代表用戶。 我從手機APP收到一個access_token,發送到我的Web API。 Web API 使用此令牌調用 GRAPH API 以獲取用戶的配置文件詳細信息。 下面是我的代碼 Startup.cs 文件

 services.AddAuthentication("JwtBearer")
                        .AddJwtBearer("JwtBearer", options =>
                        {
                            options.MetadataAddress = $"https://login.microsoftonline.com/{Configuration["b2bAzureAppIdentity:TenantId"]}/v2.0/.well-known/openid-configuration";
                            options.TokenValidationParameters = new TokenValidationParameters()
                            {
                                ValidIssuer = $"https://sts.windows.net/{Configuration["b2bAzureAppIdentity:TenantId"]}/",

                                // as audience, both the client id and the identifierUri are allowed (sematically equivalent)
                                ValidAudiences = new[] { Configuration["b2bAzureAppIdentity:AppIdUri"], Configuration["b2bAzureAppIdentity:ClientId"] }
                            };
                        }).AddMicrosoftIdentityWebApi(Configuration, "b2bAzureAppIdentity")
                        .EnableTokenAcquisitionToCallDownstreamApi()
                        .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                        .AddInMemoryTokenCaches();

controller.cs

 [HttpGet("GetMyDetails")]
    [AuthorizeForScopes(Scopes = new string[] { "user.read" })]
    public async Task<IActionResult> GetMyDetails()
    {
        var user = await _graphServiceClient.Me.Request().GetAsync();
        return new OkObjectResult(user.Photo);
    }

Appsettings 采用以下格式

 "b2bAzureAppIdentity": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "",
"TenantId": "",
"ClientId": "",
"ClientSecret": "",
"AppIdUri": ""},
 "DownstreamApi": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"},

In Azure, the API permissions and scope are set correctly, this is evident because when I make calls from postman, I'm able to get the accesstoken for on_behalf_of and use it to get the user's profile details by calling https://graph. microsoft.com/v1.0/me

在 controller 這一行

var user = await _graphServiceClient.Me.Request().GetAsync();

我收到一條錯誤消息:“沒有向 AcquireTokenSilent 調用傳遞任何帳戶或登錄提示。”

我已經用谷歌搜索了這個錯誤,解決方案說用戶應該同意 scope 但是它已經得到了 Azure 門戶中的管理員的同意。 此外,這在 Postman 中工作的事實讓人相信 APP 和 API 的配置是正確的。 在此處輸入圖像描述

有沒有人遇到過類似的問題?

發生這種情況是因為收到的 access_token 沒有與獲取用戶詳細信息的請求一起發送。 以下是如何代表提供者實施的示例:

// Create a client application.
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithTenantId(tenantID)
                // The Authority is a required parameter when your application is configured 
                // to accept authentications only from the tenant where it is registered.
                .WithAuthority(authority)
                .WithClientSecret(clientSecret)
                .Build();
                
// Use the API reference to determine which scopes are appropriate for your API request.
// e.g. - https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http
var scopes = new string[] { "User.Read" };
// Create an authentication provider.
ClientCredentialProvider authenticationProvider = new OnBehalfOfProvider(confidentialClientApplication, scopes);

var jsonWebToken = actionContext.Request.Headers.Authorization.Parameter;
var userAssertion = new UserAssertion(jsonWebToken);
// Configure GraphServiceClient with provider.
GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);
// Make a request
var me = await graphServiceClient.Me.Request().WithUserAssertion(userAssertion).GetAsync();

在這種情況下,令牌會在對WithUserAssertion的調用中添加到請求中。

請讓我知道這是否有幫助,如果您還有其他問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM