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).