【问题标题】:Is it possible to have multiple audiences with clientIds and secrets?是否可以有多个具有 clientIds 和 secrets 的受众?
【发布时间】:2020-05-01 23:08:15
【问题描述】:

使用 Microsoft.Owin.Security.Jwt,您可以执行以下操作:

public static void ConfigureOAuth(IAppBuilder app)
{
    OAuthConfiguration oAuthConfiguration = OAuthConfiguration.GetConfig("oauth");

    List<string> audiences = new List<string>();
    List<byte[]> secrets = new List<byte[]>();

    foreach (var oAuthAudienceElement in /*configuration*/)
    {
        audiences.Add(/*configuration thingy*/);
        secrets.Add(TextEncodings.Base64Url.Decode(/*configuration thingy*/));
    }

    // Api controllers with an [Authorize] attribute will be validated with JWT
    app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new List<string>(audiences),
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(oAuthConfiguration.Issuer.Domain, secrets)
            }
        });
}

但我无法在 ASP.NET Core 2.X 中找到与之等效的版本。这是不支持还是我错过了什么?我的意思是,services.AddJwtBearer 提供的不多:

services.AddAuthentication("oauth")
    .AddOAuth("oauth", options =>
    {
        // something?
    })
    .AddJwtBearer("oauth", options =>
    {

        options.TokenValidationParameters = new TokenValidationParameters
        {
            // These don't exist as in the Microsoft.Owin.Security.Jwt example above...
            // AuthenticationMode = AuthenticationMode.Active,
            // AllowedAudiences = new List<string>(audiences),
            // IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            // {
            //     new SymmetricKeyIssuerSecurityTokenProvider(oAuthConfiguration.Issuer.Domain, secrets)
            // }
        };
    });

【问题讨论】:

  • 嗯,肯定是AddJwtBearer 接受Bearer 令牌。 TokenValidationParameters 上有一个 ValidAudiences 属性供观众使用。您应该也可以在那里设置对称签名密钥。
  • @juunas 我确实看到ValidAudiences 在那里。至于 .NET 中的 IssuerSecurityTokenProviders ,您的意思是它在 .NET Core 中的等价物是 IssuerSigningKeys?我的意思是,一个是“提供者”,另一个不是。遗憾的是,这方面似乎没有很多资源。

标签: rest asp.net-core jwt


【解决方案1】:

您应该使用AddJwtBearer() 而不是AddOAuth()

TokenValidationParameters 中,受众、颁发者和签名密钥都可以接受IEnumerable 作为输入,因此您可以指定多个值(注意所有属性名称都是复数形式):

options.TokenValidationParameters = new TokenValidationParameters
{
    ValidAudiences = new [] {"audience1", "audience2" },
    ValidIssuers = new[] { "issuer1", "issuer2" },
    IssuerSigningKeys = secrets.Select(secret => new SymmetricSecurityKey(secret))
};

【讨论】:

    猜你喜欢
    • 2019-08-25
    • 2019-08-12
    • 2016-04-17
    • 2010-12-24
    • 2018-04-18
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多