I have an Mulit-tenant application using KeyCloak as Identity Broker.
There is TenantId in token through which , we will be able to identity which Tenant’s user it is.
Now, when authenticating the token, we use AddJwtBearer with Authority.
I want that Authority to be fetched from configuration based on TenantId.
Is there any way to achieve this?
public static class KeycloakAuthenticationExtensions
{
public static void AddKeycloakAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var jwtConfiguration = configuration.GetSection(Core.Authentication.Constants.JwtConfigurationSection).Get();
services.AddOptions<JwtConfiguration>().Bind(configuration.GetSection(Authentication.Constants.JwtConfigurationSection));
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = jwtConfiguration!.Authority;
options.SaveToken = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudiences = jwtConfiguration.Audiences,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
//https://learn.microsoft.com/en-us/aspnet/core/security/authentication/claims?view=aspnetcore-6.0#extend-or-add-custom-claims-using-iclaimstransformation
//Name claim and role claim mapping
NameClaimType = ApiConstants.PreferredUserNameClaim
};
options.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return context.Response.WriteAsync(context.Request.Headers[ApiConstants.AuthorizationHeader].ToString());
},
OnTokenValidated = context =>
{
return Task.CompletedTask;
}
};
});
services.AddSingleton<ITokenProvider, KeyCloakJwtTokenProvider>();
services.AddSingleton<ITokenStore, InMemoryCachedTokenStore>();
services.AddTransient<AuthenticationHttpMessageHandler>();
services.AddHttpClient<ITokenProvider, KeyCloakJwtTokenProvider>(client =>
{
client.BaseAddress = new Uri(jwtConfiguration!.Authority + ApiConstants.TokenEndpoint);
});
}
}
I have changed that jwtConfiguration to be a list of Tenants information.
For each request , AddJwtBearer is called to validate the token. Based on tenant Id coming as part of token I want to Set Authority and validate the token.