Blazor Server 中 ApiController 的授权

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

起点:

  • 一个azure租户+azure AD/Entra;
  • 一个
    blazor server app
    部署在应用服务上(+应用注册和托管身份)
    • 后面有
      ApiController
      授权访问者
  • one
    azure function
    (+ 应用程序注册和托管身份)
    • 通过
      HttpClient
      + 不记名代币
    • 通过队列存储触发
  • 一切都基于
    .net6
    (暂时没有计划迁移到
    .net8

在 Azure 中尝试访问 api 时,我收到 401 HTTP 响应代码;在开发过程中,我收到 302 响应,这最终导致“软故障”(= 不调用 api)。

(注意:Blazor 服务器主要角色是具有组织帐户身份验证的 SPA;

ApiController
用于接收来自 Azure 功能的通知)

我已在 Blazor 应用程序注册中为应用程序创建了应用程序角色,并授予了 Azure 功能的权限;我什至在 Blazor 应用程序注册中公开了 API,并授予了 Azure 函数的权限(尽管这被列为委派权限,我想这根本没有帮助)。

我知道一个可能的解决方案,我可以摆脱 ApiController 并将两个应用程序绑定到 SignalR 集线器(因为这基本上是我目前想要实现的目标),但这并不能解决如何访问此类API 控制器。

我想我需要配置 Blazor 服务器应用程序以接受不记名令牌,但由于我对整个生态系统相对较新,我不确定该部分到底应该是什么样子。

欢迎任何帮助,谢谢。

Update
:我在
Program.cs
代码中添加了以下内容:

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

现在ApiCall成功了,但是它覆盖了之前添加的部分

builder.Services
    .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .[ommited]

似乎下一步是将这两者结合起来,并使用 OpenId 进行 Web 交互,使用 JWT 进行 api 调用... - 完成。

Continuation
(编辑第2号)

我发布的答案适用于 localhost,但当所有内容都部署在 azure 生态系统中时,我仍然收到 401。似乎我缺少一些天蓝色的配置点...

azure-functions authorization blazor-server-side azure-managed-identity asp.net-apicontroller
1个回答
0
投票

解决方案出乎意料地简单。

Program.cs
我更换了

builder.Services
    .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme);
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .[ommited];

与:

var auth = builder.Services
    .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme);
auth.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .[ommited];
auth.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

并调整

[Authorize]
属性以使用
"Bearer"
架构:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
© www.soinside.com 2019 - 2024. All rights reserved.