[英]How to create Microsoft GraphServiceClient in ASP.NET Core Web Api 6
我有一個 ASP.NET Core Web Api 6 項目,由 VS 2022 生成,具有 MicrosoftIdentity 身份驗證。 填寫了登錄AzureAd所需的標識符,AzureAD:ClientSecret也保存在secrets.json中。
它看起來像這樣:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
builder.Services.AddAuthorization();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
var scopeRequiredByApi = app.Configuration["AzureAd:Scopes"] ?? "";
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "xxxxxxxxx",
"TenantId": "xxxxxxxxxxxxxxxxxxxxxxxxxxx,
"ClientId": "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
"CallbackPath": "/signin-oidc",
"Scopes": "access_as_user",
"ClientSecret": "Client secret from app-registration. Check user secrets/azure portal.",
"ClientCertificates": []
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MicrosoftGraph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
}
}
標識符已替換為文本 xxxxx。
我需要為“獲取用戶”調用 MicrosoftGraph 服務,例如 api。
Microsoft 文檔列出了這段代碼:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var user = await graphClient.Users["{user-id}"]
.Request()
.GetAsync();
ASP.NET Web Api 項目的上述配置包含了授權所需的所有標識符。
如何使用上述上下文中配置的標識符創建authProvider變量?
好吧,謝謝。
這條線
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
通過依賴注入添加對GraphServiceClient
的支持
在您的 controller: 中,將GraphServiceClient
參數添加到構造函數中,依賴注入將使用配置的authProvider
解析GraphServiceClient
的實例。
public class YourController
{
private GraphServiceClient _graphServiceClient;
public YourController(GraphServiceClient graphServiceClient)
{
_graphServiceClient = graphServiceClient;
}
...
}
謝謝。 我使用“最小的 api”,所以這也應該有效:
app.MapGet("/getuser", (Microsoft.Graph.GraphServiceClient client) =>
{
return (new MsTeamsMe().Run(client));
});
不幸的是,這樣配置的 GraphServiceClient 客戶端無法正常工作。 所以在我看來,由於授權的復雜性,手動生成一個功能性的 GraphServiceClient 實例更安全:
GraphServiceClient CreateClient()
{
var scopes = new string[] { "https://graph.microsoft.com/.default" };
var tenantId = TeamsConstants.TenantId;
// Configure the MSAL client as a confidential client
var confidentialClient = ConfidentialClientApplicationBuilder
.Create(TeamsConstants.ClientId)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}/v2.0")
.WithClientSecret(TeamsConstants.ClientSecretValue)
.Build();
// Build the Microsoft Graph client. As the authentication provider, set an async lambda
// which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
// and inserts this access token in the Authorization header of each API request.
return new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient
.AcquireTokenForClient(scopes)
.ExecuteAsync();
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
})
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.