ASP.NET Core 和 Microsoft Graph

问题描述 投票:0回答:1

我有一个 ASP.NET Core Web 应用程序。 用户可以使用用户名和密码或 Azure AD 登录。

在包含许多信息的页面中,我想仅为 Azure AD 用户显示来自图表的信息(例如未读电子邮件计数器)。其他用户只需查看该页面,无需“未读电子邮件计数器”信息。

我不明白如何让它发挥作用。 问题是,只有当我用以下内容装饰页面时,图表才有效

[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]

但为了允许其他用户访问同一页面,我无法使用该属性。

两者

[Authorize(AuthenticationSchemes = $"{OpenIdConnectDefaults.AuthenticationScheme},{CookieAuthenticationDefaults.AuthenticationScheme}")]

[AllowAnonymous]
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]

适用于其他用户,但不适用于 Azure AD 用户,因为图形会抛出异常

InvalidOperationException: IDW10503: Cannot determine the cloud Instance. The provided authentication scheme was ''. Microsoft.Identity.Web inferred 'Cookies' as the authentication scheme. Available authentication schemes are 'Cookies,OpenIdConnect'.

这里有一些代码供您参考:

认证

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddNegotiate()
    .AddMicrosoftIdentityWebApp(builder.Configuration, configSectionName: "Authentication:AzureAD");

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

app.UseSession();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

剃刀页面

[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public class GraphCMSModel : PageModel
{
    private readonly GraphLogic _graphLogic;

    public string Message { get; set; } = string.Empty;

    public GraphCMSModel(GraphLogic graphLogic)
    {
        _graphLogic = graphLogic;
    }

    public async Task OnGetAsync()
    {
        if (AuthHelper.IsAzureAdAuthenticated)
        {
            var messages = await _graph.Me.MailFolders["Inbox"].Messages
                                  .Request()
                                  .Filter("isRead ne true")
                                  .GetAsync();
            Message = $"You have {messages.Count} unread messages";
        }
        else
        {
            Message = "No Graph for you";
        }
    }
}
asp.net-core microsoft-graph-api asp.net-identity
1个回答
0
投票

我找到了一种方法来告诉 GraphServiceClient 使用 WithAuthenticationScheme 方法使用什么身份验证模式:

var messages = await graph.Me.MailFolders["Inbox"].Messages
    .Request()
    .WithAuthenticationScheme(OpenIdConnectDefaults.AuthenticationScheme)
    .Filter("isRead ne true")
    .GetAsync();
© www.soinside.com 2019 - 2024. All rights reserved.