【问题标题】:.NET 5 API and React UI authentication using Azure AD B2C - Bearer error="invalid_token", error_description="The signature is invalid".NET 5 API 和 React UI 身份验证使用 Azure AD B2C - Bearer error="invalid_token", error_description="签名无效"
【发布时间】:2021-08-19 00:00:54
【问题描述】:

作为新项目的一部分,我正在尝试使用 Azure AD B2C 将身份验证与 React 应用和 .NET 5 API 集成。我想我快到了,但是在发出请求时,我收到一条带有“Bearer error="invalid_token", error_description="The signature is invalid" 的 401 消息。

  • 我已经在 Azure AD B2C 中注册了 API 和 React 应用。
  • 我已从 React 应用授予 API 权限。
  • 我已经创建了一个测试范围来开始
  • 我可以登录到我的 React 应用程序并获得一个不记名令牌。
  • 如果我检查令牌,我可以看到受众是我的带有客户端 ID 的 API。
  • 如果我提出请求,它会将令牌传递给 API,正如我所相信的那样。

在我的 Startup.cs 中,我将其定义如下:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"))

我的测试控制器端点是这样写的:

[Authorize]
[HttpGet("private")]
public IActionResult Private()
{
    return Ok(new
    {
        Message = "Hello from a private endpoint! You need to be authenticated to see this."
    });
}

我的 appsettings.json 中有我的 AzureADB2C 设置,如下所示:

"AzureAdB2C": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "<API Client Id (GUID)>",
    /*
      You need specify the TenantId only if you want to accept access tokens from a single tenant
     (line-of-business app).
      Otherwise, you can leave them set to common.
      This can be:
      - A GUID (Tenant ID = Directory ID)
      - 'common' (any organization and personal accounts)
      - 'organizations' (any organization)
      - 'consumers' (Microsoft personal accounts)
    */
    "TenantId": "common"
  },

在某些情况下,我正在处理各种过时的文档,并且给出的示例使用 node.js API 而没有 .NET API 示例,因此我尝试尽我所能将所有内容拼凑起来,我'我不太确定我错过了什么。

【问题讨论】:

    标签: c# reactjs azure azure-active-directory .net-5


    【解决方案1】:

    如果你想在 Azure AD B2C 中使用 Net Core Web API,我们需要更新 appsetting.json 如下

     "AzureAdB2C": {
        "Instance": "https://xxx.b2clogin.com",
        "ClientId": "",
        "Domain": "xxx.onmicrosoft.com",
        "SignUpSignInPolicyId": "B2C_1A_signup_signin"
      },
    
    

    更多详情请参考blogblogsample

    另外,关于如何将 Azure AD B2C 与 React 应用集成,请参考here

    【讨论】:

    • 谢谢,我做了一些更改,看起来我可能一直遵循 AzureAD 指导,而不是 B2C,这无济于事。这些示例表明不需要 TenantId,但是如果我省略它,错误详细信息会说这是必需的。如果我添加回来,则会给出错误IDX20803: Unable to obtain configuration from: 'https://&lt;mytenant&gt;.b2clogin.com/common/v2.0/.well-known/openid-configuration'
    • 另外,如果我更改为我的实际 TenantId 的 common,我会得到一个 404,当我从 Azure 门户复制它时,这似乎很奇怪。
    猜你喜欢
    • 2018-08-03
    • 2020-12-24
    • 2020-10-08
    • 1970-01-01
    • 2021-02-06
    • 2020-06-03
    • 2021-07-26
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多