【发布时间】:2023-01-27 20:54:34
【问题描述】:
我有一个由 VS 2022 生成的 ASP.NET Core Web Api 6 项目,具有 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 项目的上述配置包含了授权所需的所有标识符。
如何创建一个授权提供者在上述上下文中使用配置的标识符的变量?
好吧,谢谢。
【问题讨论】:
标签: c# api asp.net-core authentication microsoft-graph-api