我正在try 使用Microsoft Entra ID进行身份验证和Microsoft Graph API来访问页面,使用带有PKCE的授权码流进行应用程序注册,并锁定Entra ID中特定安全组的某些页面.我使用Visual Studio创建Blazor项目,并使用"Connected Services"添加Microsoft Identity Platform以在我的租户上创建应用程序注册.这运行得很好,我能够通过使用我的Entra ID帐户进行身份验证来访问我的页面.然而,我在Program.cs中添加了一些额外的行,以便能够使用Microfoft Graph添加授权和判断用户组成员身份,这就是一切都出错的时候.我可以使用Entra ID进行身份验证,并且可以正常查看我的页面,直到我在"AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))".后面添加了这3行然后它就给了我那个错误.

这不起作用:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "User.Read.All", "Group.Read.All" }) /*new string[] { "User.Read.All", "Group.Read.All" }*/
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();

这是可行的:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))

我还有一个Secrets.json连接服务,它只有以下json内容:

"AzureAD:ClientSecret": "xxx-My Secret-xxx" //Not my actual secret, obviously

And this is my global "appsettings.json": enter image description here

There is also another "appsettings.json" under "wwwroot" like this:enter image description here

however the content in the "appsettings.json" under "wwwroot" is like this: enter image description here

同样,当我不包括后面的3行时

.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd))
  • 它工作得很好.我可以用我的Entra ID帐户登录,然后使用页面.然而,在其上方添加这三行不再起作用.我需要能够做到这一点,以便在网络应用程序中的某些页面,只有特定的安全组成员与入口ID可以访问它们.

Here is how the app registration is set up: enter image description here

enter image description here

我怎么才能解决这个问题?我试着将Secrets.json中的ClientSecret值设置为空字符串,但是它抱怨我需要提供Secret.当我不这样做的时候,它会抱怨我应该这样做.

Extra: It says: 0 web, 6 spa, 0 public enter image description here

非常困惑.帮助?

Program.cs:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "User.Read.All", "Group.Read.All" }) /*new string[] { "User.Read.All", "Group.Read.All" }*/
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();

builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();
builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();

推荐答案

我使用以下代码在Blazor Web应用程序中使用Graph API实现了Azure AD,该应用程序使用交互呈现模式:服务器.

我通过Visual Studio中的连接服务连接了Azure AD.

Program.cs:

using BlazorApp26.Components;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "User.Read.All" }) 
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();

builder.Services.AddControllersWithViews()
                    .AddMicrosoftIdentityUI();
builder.Services.AddAuthorization(options =>
{
      options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();
builder.Services.AddScoped<SignOutSessionStateManager>();
builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);   
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseRewriter(new RewriteOptions().Add(
    context =>
    {
        if (context.HttpContext.Request.Path ==
                "/MicrosoftIdentity/Account/logout")
            context.HttpContext.Response.Redirect("/");
    }));
app.UseAntiforgery();
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();
app.Run();

这是我的根文件夹应用程序设置.

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "microsoft.onmicrosoft.com",
    "TenantId": "<TenantId>",
    "ClientId": "<ClientId>",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": "<ClientSecret>"
  },
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes":  "User.Read.All"
  },
  "AllowedHosts": "*"
}

wwwroot/appsettings.json:

{
  "AzureAd": {
    "ClientId": "<ClientId>",
    "Authority": "https://login.microsoftonline.com/M365x56209219.onmicrosoft.com",
    "ValidateAuthority": true
  },
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "User.Read.All"
  }
}

Blazor WebApp:Raw例外:AADSTS700025:"client_assertion" and "client_secret" should not be displayed because the client已公开

对于上面的错误,点击App注册,然后认证-&>添加一个平台-&>Web,它将重定向到配置Web.我添加了重定向URI,如下所示.

enter image description here

enter image description here

启用访问令牌和ID令牌,如下所示.

enter image description here

Output:

enter image description here

Csharp相关问答推荐

List T.AddRange在传递ConcurrentDictionary作为参数时引发ArgumentExcellent

如何使用Automapper映射两个嵌套列表

Monty Hall游戏节目模拟给我50/50的结果

如果存在对CodeAnalysis.CSharp的引用,则不能引用netStandard2.0库

将现有字段映射到EFCore中的复杂类型

我想在文本框悬停时在其底部显示一条线

WinForms在Linux上的JetBrains Rider中的应用

如何使用EF Core和.NET 8来upsert到具有多对多关系的表?

如何使用MoQ模拟Resources GroupCollection?

将字节转换为 struct 并返回

具有以接口为其类型的属性的接口;类指定接口的实现,但无效

如何在我的C#应用程序中设置带有reactjs前端的SignalR服务器?

带有列表参数的表达式树

将操作从编辑页重定向到带参数的索引页

数据库.Migrate在对接容器重启时失败

如何使用ODP.NET C#设置Oracle会话时间长度限制

避免在特定区域中设置Visual Studio代码的自动格式

C#-如何将int引用获取到byte[]

反编译源代码时出现奇怪的字符

在c#中,使用Okta和Blazor时,LocalReDirect()陷入循环,出现错误&请求太多.