我正在尝试获取一些图表以从 Entra 返回一些用户属性。我需要使用
graphClient.Me.GetAsync()
。当我从 Visual Studio 运行项目时,系统会提示我输入 Entra 凭据,然后收到以下错误消息:
处理请求时发生未处理的异常。
TypeLoadException:无法从程序集“Microsoft.Graph.Core,Version=3.1.22.0,Culture=neutral,PublicKeyToken=xxxxxxxxxxxx”加载类型“Microsoft.Graph.IAuthenticationProviderOption”。
这是我的设置 - 我添加了这些包:
Microsoft.Graph v.5.61
Microsoft.Identity.Web 3.2.2
Microsoft.Identity.Web.MicrosoftGraph v. 3.2.2
添加到
appsettings.json
:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "yourdomain.onmicrosoft.com",
"TenantId": "your-tenant-id",
"ClientId": "your-client-id",
"ClientSecret": "your-client-secret",
"CallbackPath": "/signin-oidc"
}
}
添加到
Program.cs
:
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
var builder = WebApplication.CreateBuilder(args);
// Add authentication and Microsoft Identity
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
// Add Graph API client
builder.Services.AddMicrosoftGraph(options =>
{
options.Scopes = "User.Read"; // Ensure this scope is granted in Azure portal
});
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
这是我的控制器:
[Authorize]
public class HomeController : Controller
{
private readonly GraphServiceClient _graphClient;
public HomeController(GraphServiceClient graphClient)
{
_graphClient = graphClient;
}
public async Task<IActionResult> Index()
{
// Get the user's information
var user = await _graphClient.Me.GetAsync();
// Access the user's email
var email = user.Mail ?? user.UserPrincipalName;
ViewBag.Email = email;
return View();
}
}
对我做错了什么有什么想法吗?
我尝试过不同版本的软件包,
Program.cs
中的不同代码。
为了修复该错误,我卸载了
Microsoft.Graph
软件包并更新了 Program.cs 和 HomeController.cs 中的代码,以使用 Microsoft Graph 从 Entra 检索用户属性。
.csproj:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.10" NoWarn="NU1605" />
<PackageReference Include="Microsoft.Identity.Web" Version="2.19.1" />
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="2.19.1" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="2.19.1" />
<PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.15.2" />
</ItemGroup>
程序.cs:
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ?? builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
builder.Services.AddRazorPages()
.AddMicrosoftIdentityUI();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
HomeController.cs:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
using Microsoft.Identity.Web;
namespace WebApplication15.Controllers
{
[Authorize]
public class HomeController : Controller
{
private readonly GraphServiceClient _graphClient;
public HomeController(GraphServiceClient graphClient)
{
_graphClient = graphClient;
}
[AuthorizeForScopes(ScopeKeySection = "MicrosoftGraph:Scopes")]
public async Task<IActionResult> Index()
{
var user = await _graphClient.Me.Request().GetAsync();
ViewData["GraphApiResult"] = user.UserPrincipalName;
return View();
}
}
}
appsettings.json:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "<domain>",
"TenantId": "<tenantID>",
"ClientId": "<clientID>",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MicrosoftGraph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
}
}
输出:
成功登录后,我在浏览器中的Graph详细信息下得到了电子邮件地址,如下所示。