【问题标题】:How to use multiple Aws Cognito Userpools in AddAuthentication() in a ASP.NET CORE 2.1 API如何在 ASP.NET CORE 2.1 API 的 AddAuthentication() 中使用多个 Aws Cognito 用户池
【发布时间】:2019-08-26 08:04:37
【问题描述】:

我目前遇到的问题是我有一个 ASP.NET CORE API,我们在其中使用 Aws Cognito 用户来授权对 API 的访问,而且效果很好。现在我们需要使用第二个用户池进行授权,这样两个不同的用户池就可以访问 API。 我在如何在 AddAuthentication/AddJwtBearer 中添加多个受众/权限时遇到了一些麻烦,似乎这些方法不能采用两个同名的模式,“Bearer”,有人知道怎么做吗?

我已经尝试添加多个 AddJwtBearer,这会导致 API 崩溃。尝试了不同的东西,但大多数解决方案使用多个受众,但从不同时谈论多个权威,如果这有意义的话。

目前是这样的

 services.AddAuthentication("Bearer")
                   .AddJwtBearer(options =>
                   {
                       options.Audience = "AUDIENCE";
                       options.Authority = "AUTHORITY";
                   });

我想要这样的东西

 services.AddAuthentication("Bearer")
                   .AddJwtBearer(options =>
                   {
                       options.Audience = "AUDIENCE";
                       options.Authority = "AUTHORITY";
                   })
                  .AddJwtBearer(options =>
                   {
                       options.Audience = "AUDIENCE2";
                       options.Authority = "AUTHORITY2";
                   });

目标是我希望两个用户池的用户都能够授权 API,提前感谢您的帮助!

【问题讨论】:

  • 我自己也在做类似的事情。见this issue。
  • Yir 我读了那个帖子,但遗憾的是没有回答我的问题,目前看起来不支持。

标签: c# amazon-web-services api asp.net-core amazon-cognito


【解决方案1】:

您必须像以前一样添加多个承载,但名称不同。

services
    .AddAuthentication()
    .AddJwtBearer("Bearer1", options =>
    {
        options.Audience = "AUDIENCE";
        options.Authority = "AUTHORITY";
    })
    .AddJwtBearer("Bearer2", options =>
    {
        options.Audience = "AUDIENCE2";
        options.Authority = "AUTHORITY2";
    });

那么以后就不用UseAuthentication()了,就得自己添加自定义中间件了。

app.Use(async (context, next) =>
{
    var result = await context.AuthenticateAsync("Bearer1");
    if (!result.Succeeded)
    {
        result = await context.AuthenticateAsync("Bearer2");
    }

    context.User = result.Principal;

    await next();
});

我自己没有尝试过,只是从 cmets 中拼凑出来的,所以如果它适合你,请告诉我。

【讨论】:

  • 嗨,伙计,很抱歉回复晚了,我正在做其他任务,但现在我有时间实施您的解决方案,我可以说谢谢。就像我想要的那样工作,现在两个用户池都可以授权 API! TY
猜你喜欢
  • 2020-12-22
  • 2018-03-25
  • 2022-01-11
  • 2021-04-26
  • 2020-11-27
  • 2017-11-23
  • 2020-05-28
  • 2019-05-18
  • 2021-01-24
相关资源
最近更新 更多