Aspire Support
.NET Aspire is an opinionated, cloud ready stack for building observable, production ready, distributed applications.
Keycloak.AuthServices.Aspire.Hosting
adds a support to run Keycloak Instance as a component. It is intended to be used together with Keycloak.AuthServices
.
See working example here. Examples/Aspire + Web API
Add to existing application
Install Keycloak.AuthServices.Aspire.Hosting package to "AppHost":
dotnet add package Keycloak.AuthServices.Aspire.Hosting
Modify the AppHost/Program.cs
:
// AppHost/Program.cs
var builder = DistributedApplication.CreateBuilder(args);
var keycloak = builder
.AddKeycloakContainer("keycloak");
var realm = keycloak.AddRealm("Test");
builder.AddProject<Projects.Api>("api").WithReference(keycloak).WithReference(realm);
builder.Build().Run();
Here is what it does:
- Starts the instance of Keycloak as docker container.
WithReference(keycloak)
adds Keycloak server instance to Service Discovery.WithReference(realm)
addsKeycloak__Realm
andKeycloak__AuthServerUrl
environment variables.
From this point you are almost finished, the only this is left is to configure Authentication missing parts:
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;
builder.AddServiceDefaults();
services.AddKeycloakWebApiAuthentication(
configuration,
options =>
{
options.Audience = "workspaces-client";
options.RequireHttpsMetadata = false;
}
);
services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/hello", () => "Hello World!").RequireAuthorization();
app.Run();
Run:
dotnet run --project ./AppHost
Import configuration files
You can reference import files and bind Keycloak data volumes to persist Keycloak configuration and share it with others.
var builder = DistributedApplication.CreateBuilder(args);
var keycloak = builder
.AddKeycloakContainer("keycloak")
.WithDataVolume()
.WithImport("./KeycloakConfiguration/Test-realm.json")
.WithImport("./KeycloakConfiguration/Test-users-0.json");
var realm = keycloak.AddRealm("Test");
builder.AddProject<Projects.Api>("api").WithReference(keycloak).WithReference(realm);
builder.Build().Run();
TIP
You can sync your current configuration via CLI
Inside docker container run:
/opt/keycloak/bin/kc.sh export --dir /opt/keycloak/data/import --realm Test
Start from Template
You can use Keycloak.AuthServices.Templates to scaffold the new Aspire Project that has Keycloak.AuthServices
integration configured.
Install template:
dotnet new install Keycloak.AuthServices.Templates
Scaffold a solution:
dotnet new keycloak-aspire-starter -o $dev/KeycloakAspireStarter --EnableKeycloakImport
See Aspire Template for more details.