Posted on • Originally published atnikiforovall.github.io on
Using Keycloak in .NET Aspire projects
TL;DR
You can useKeycloak.AuthServices.Templates to add Keycloak support for .NET Aspire projects. See the docs for more details -Keycloak.AuthServices/Aspire Support.
Source code:https://github.com/NikiforovAll/keycloak-aspire-starter-template
Introduction
From the officialdocs:
.NET Aspire is designed to improve the experience of building .NET cloud-native apps. It provides a consistent, opinionated set of tools and patterns that help you build and run distributed apps.
Personally, I’m a big fan of Aspire because it enables great developer experience and productivity. I recommend trying it on your own 🚀
This article will show you how to get started with Keycloak and Aspire. It is based onKeycloak.AuthServices.Templates template. Templates make it really easy to get started.
💡Here is a basic example of how the integration looks like:
varbuilder=DistributedApplication.CreateBuilder(args);varkeycloak=builder.AddKeycloakContainer("keycloak").WithDataVolume();varrealm=keycloak.AddRealm("Test");builder.AddProject<Projects.Api>("api").WithReference(realm);builder.Build().Run();
Scaffold a solution
Install a templates pack:
❯ dotnet newinstallKeycloak.AuthServices.Templates# The following template packages will be installed:# Keycloak.AuthServices.Templates::2.5.0# Success: Keycloak.AuthServices.Templates::2.5.0 installed the following templates:# Template Name Short Name Language Tags# ----------------------- ----------------------- -------- -------------------------------------# Keycloak Aspire Starter keycloak-aspire-starter [C#] Common/.NET Aspire/Cloud/API/Keycloak# Keycloak WebApi keycloak-webapi [C#] Common/API/Keycloak❯ dotnet new keycloak-aspire-starter-o$dev/keycloak-aspire-starter-template# The template "Keycloak Aspire Starter" was created successfully.
Here is what was generated:
❯ tre.├── .gitignore├── Api│ ├── Api.csproj│ ├── Extensions.OpenApi.cs│ ├── Program.cs│ ├── Properties│ │ └── launchSettings.json│ ├── appsettings.Development.json│ └── appsettings.json├── AppHost│ ├── AppHost.csproj│ ├── KeycloakConfiguration│ │ ├── Test-realm.json│ │ └── Test-users-0.json│ ├── Program.cs│ ├── Properties│ │ └── launchSettings.json│ ├── appsettings.Development.json│ └── appsettings.json├── Directory.Build.props├── Directory.Packages.props├── README.md├── ServiceDefaults│ ├── Extensions.cs│ └── ServiceDefaults.csproj├── global.json└── keycloak-aspire-starter-template.sln
Run it
❯ dotnet run--project ./AppHost/# Building...# info: Aspire.Hosting.DistributedApplication[0]# Aspire version: 8.0.1+a6e341ebbf956bbcec0dda304109815fcbae70c9# info: Aspire.Hosting.DistributedApplication[0]# Distributed application starting.# info: Aspire.Hosting.DistributedApplication[0]# Application host directory is: C:\Users\Oleksii_Nikiforov\dev\keycloak-aspire-starter-template\AppHost# info: Aspire.Hosting.DistributedApplication[0]# Now listening on: http://localhost:15056# info: Aspire.Hosting.DistributedApplication[0]# Distributed application started. Press Ctrl+C to shut down.
Here are resources from Aspire Dashboard:

As you can see, there is aquay.io/keycloak/keycloak:24.0.3
container running. It is available on your local machine:http://localhost:8080/. Useadmin:admin
credentials.
The template project was generated with exemplary import files. It importsTest realm, addsworkspaces-client, and seeds test users:

Now, we can open Swagger UI and retrieve an access token. Note, imported realm is configured to supportImplicit Flow. We can use it during the development process as demonstrated below.

To invoke the API you can use Swagger UI or other HTTP tool of your choice. Here is an example of how to usecURL
:
curl-X'GET'\'https://localhost:51492/hello'\-H'accept: text/plain'\-H'Authorization: Bearer <AUTH_TOKEN>'# Hello World!
Code Explained
Basically, to setup Keycloak installation with Aspire we need to setup two things:
- Add Keycloak Resource to Aspire
AppHost
. - Configure Web API to target Keycloak installation
Here is how to add Keycloak as resource to Aspire:
// AppHost/Program.csvarbuilder=DistributedApplication.CreateBuilder(args);varkeycloak=builder.AddKeycloakContainer("keycloak").WithDataVolume().WithImport("./KeycloakConfiguration/Test-realm.json").WithImport("./KeycloakConfiguration/Test-users-0.json");varrealm=keycloak.AddRealm("Test");builder.AddProject<Projects.Api>("api").WithReference(keycloak).WithReference(realm);builder.Build().Run();
The code above does the following:
- Starts a Keycloak Instance
- Imports realm and test users
- Reference to Keycloak adds Keycloak to service discovery
- Reference to Realm addsKeycloak__Realm andKeycloak__AuthServerUrl environment variables.
And here is how to configureApi
to integrated with Keycloak and useworkspaces-client:
// Api/Program.csusingApi;usingKeycloak.AuthServices.Authentication;varbuilder=WebApplication.CreateBuilder(args);varservices=builder.Services;varconfiguration=builder.Configuration;builder.AddServiceDefaults();services.AddApplicationOpenApi(configuration);services.AddKeycloakWebApiAuthentication(configuration,options=>{options.Audience="workspaces-client";options.RequireHttpsMetadata=false;});services.AddAuthorization();varapp=builder.Build();app.UseHttpsRedirection();app.UseApplicationOpenApi();app.UseAuthentication();app.UseAuthorization();app.MapGet("/hello",()=>"Hello World!").RequireAuthorization();app.Run();
Conclusion
The integration of Keycloak with .NET Aspire projects provides a first class support for building distributed, cloud native systems. By leveraging theKeycloak.AuthServices.Templates
template, developers can easily scaffold a solution and configure their APIs to work with Keycloak.
🙌Keycloak.AuthServices.Templates
is under development. Please, feel free to submit PRs. 🙌
References
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse