Multi-tenant (realm based) REST Web API authentication

We’re building a multi-tenant setup with a C# Web API and KeyCloak for auth and APISIX as application gateway. APISIX handles the authentication and passes an X-Access-Token to our API when authentication was successful.

I have come up with the following code:

public static class AuthExtensions
{
    private static readonly ConcurrentDictionary<string, Lazy<OpenIdConnectConfiguration>> _realmconfigurations = new();

    public static IServiceCollection AddDefaultAuth(this IServiceCollection services, IConfiguration configuration)
        => services
        .AddTransient<IClaimsTransformation, ClaimsTransformer>()
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
        {
            var baseuri = new Uri("http://keycloak.host.example/realms/");

            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateLifetime = true,
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidAudiences = ["frontend", "swagger", "app"],
                ValidateIssuerSigningKey = true,
                IssuerValidator = (issuer, securityToken, parameters) => GetConfiguration(baseuri, securityToken).Issuer,
                IssuerSigningKeyResolver = (token, securityToken, kid, parameters) => GetConfiguration(baseuri, securityToken).JsonWebKeySet.Keys
            };
            options.SaveToken = true;
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    if (context.Request.Headers.TryGetValue("X-Access-Token", out var header))
                    {
                        context.Token = header;
                    }
                    return Task.CompletedTask;
                }
            };
            options.Validate();
        }).Services
        .AddAuthorization();


    private static OpenIdConnectConfiguration GetConfiguration(Uri baseUri, SecurityToken securityToken)
    {
        var realm = GetRealmFromToken(securityToken);
        return _realmconfigurations.GetOrAdd(realm, (k) => new Lazy<OpenIdConnectConfiguration>(
               () => GetConfigurationManager(baseUri, realm).GetConfigurationAsync(CancellationToken.None).GetAwaiter().GetResult()
        )).Value;
    }

    public static IConfigurationManager<OpenIdConnectConfiguration> GetConfigurationManager(Uri baseUri, string realm)
        => new ConfigurationManager<OpenIdConnectConfiguration>(GetRealmBaseUri(baseUri, realm) + ".well-known/openid-configuration",
            new OpenIdConnectConfigurationRetriever(),
            new HttpDocumentRetriever() { RequireHttps = false }
        );

    private static Uri GetRealmBaseUri(Uri baseKeysUri, string realm) => new(baseKeysUri, Uri.EscapeDataString(realm) + "/");
    private static string GetRealmFromToken(SecurityToken securityToken) => securityToken.Issuer.Split('/')[^1];

    public static IApplicationBuilder UseDefaultAuth(this IApplicationBuilder app)
        => app
        .UseAuthentication()
        .UseAuthorization();
}

This uses the OIDC configuration for specific url from the .well-known/openid-configuration KeyCloak endpoint and caches this configuration in a ConcurrentDictionary so we have at most 1 request per realm to get this configuration and store it (and “under the hood” another request to get the jwks certs from /realms/{realm}/protocol/openid-connect/certs as far as I’m aware).

The realm is determined by taking the last element from the token’s Issuer.

I wonder, however, if this is the best way to go. In my reasoning, tokens from unknown issuers won’t be accepted because the .well-known/openid-configuration for a given ‘randomly guessed’ realm won’t exist. And for existing realms, the configuration will be retrieved from KeyCloak, including all signing keys etc. so a token can, and will, then be, validated with that configuration data. When we add a realm to KeyCloak this should be automatically ‘picked up’ in this setup. We can have cached OIDC configs in the dictionary expire every, say, hour or day or month to old/stale items can be pruned and renewed keys can be picked up (though not sure if/how they are (for example) auto-rotated, then this may require a little extra ‘trigger’ to renew our cached information).

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật