• Stars
    star
    423
  • Rank 102,544 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 3 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Authentication and Authorization with Keycloak and ASP.NET Core 🔐

Keycloak.AuthServices

Build CodeQL NuGet contributionswelcome Conventional Commits License

Easy Authentication and Authorization with Keycloak in .NET and ASP.NET Core.

Package Version Description
Keycloak.AuthServices.Authentication Nuget Keycloak Authentication JWT + OICD
Keycloak.AuthServices.Authorization Nuget Authorization Services. Use Keycloak as authorization server
Keycloak.AuthServices.Sdk Nuget HTTP API integration with Keycloak

GitHub Actions Build History

Getting Started

// Program.cs
var builder = WebApplication.CreateBuilder(args);

var host = builder.Host;
var configuration = builder.Configuration;
var services = builder.Services;

services.AddKeycloakAuthentication(configuration);

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", () => "Hello World!");

app.Run();

In this example, configuration is based on appsettings.json.

//appsettings.json
{
    "Keycloak": {
        "realm": "Test",
        "auth-server-url": "http://localhost:8080/",
        "ssl-required": "none",
        "resource": "test-client",
        "verify-token-audience": false,
        "credentials": {
        "secret": ""
        },
        "confidential-port": 0
    }
}

It's fetched based on well-known section "Keycloak". AddKeycloakAuthentication uses KeycloakAuthenticationOptions.Section under the hood.

You can always fetch the corresponding authentication options like this:

var authenticationOptions = configuration
    .GetSection(KeycloakAuthenticationOptions.Section)
    .Get<KeycloakAuthenticationOptions>();

services.AddKeycloakAuthentication(authenticationOptions);

AddKeycloakAuthentication method has several overloads. It allows to override some conventions, for example:

public static AuthenticationBuilder AddKeycloakAuthentication(
    this IServiceCollection services,
    IConfiguration configuration,
    string? keycloakClientSectionName,
    Action<JwtBearerOptions>? configureOptions = default)
{
    /* implementation */
}

Example. Authentication + Authorization

Here is how to add JWT-based authentication and custom authorization policy.

var builder = WebApplication.CreateBuilder(args);

var host = builder.Host;
var configuration = builder.Configuration;
var services = builder.Services;

host.ConfigureKeycloakConfigurationSource();
// conventional registration from keycloak.json
services.AddKeycloakAuthentication(configuration);

services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireWorkspaces", builder =>
        {
            builder.RequireProtectedResource("workspaces", "workspaces:read") // HTTP request to Keycloak to check protected resource
                .RequireRealmRoles("User") // Realm role is fetched from token
                .RequireResourceRoles("Admin"); // Resource/Client role is fetched from token
        });
    })
    .AddKeycloakAuthorization(configuration);

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/workspaces", () => "[]")
    .RequireAuthorization("RequireWorkspaces");

app.Run();

Keycloak.AuthServices.Authentication

Add OpenID Connect + JWT Bearer token authentication.

For example, see Getting Started

Adapter File. Optional

Using appsettings.json is a recommended and it is an idiomatic approach for .NET, but if you want a standalone "adapter" (installation) file - keycloak.json. You can use ConfigureKeycloakConfigurationSource. It adds dedicated configuration source.

// add configuration from keycloak file
host.ConfigureKeycloakConfigurationSource("keycloak.json");
// add authentication services, OICD JwtBearerDefaults.AuthenticationScheme
services.AddKeycloakAuthentication(configuration, o =>
{
    o.RequireHttpsMetadata = false;
});

Client roles are automatically transformed into user role claims KeycloakRolesClaimsTransformation.

See Keycloak.AuthServices.Authentication - README.md

Keycloak installation file:

// confidential client
{
  "realm": "<realm>",
  "auth-server-url": "http://localhost:8088/auth/",
  "ssl-required": "external", // external | none
  "resource": "<clientId>",
  "verify-token-audience": true,
  "credentials": {
    "secret": ""
  }
}
// public client
{
  "realm": "<realm>",
  "auth-server-url": "http://localhost:8088/auth/",
  "ssl-required": "external",
  "resource": "<clientId>",
  "public-client": true,
  "confidential-port": 0
}

Keycloak.AuthServices.Authorization

services.AddAuthorization(authOptions =>
{
    authOptions.AddPolicy("<policyName>", policyBuilder =>
    {
        // configure policies here
    });
}).AddKeycloakAuthorization(configuration);

See Keycloak.AuthServices.Authorization - README.md

Keycloak.AuthServices.Sdk

Keycloak API clients.

Service Description
IKeycloakClient Unified HTTP client - IKeycloakRealmClient, IKeycloakProtectedResourceClient
IKeycloakRealmClient Keycloak realm API
IKeycloakProtectedResourceClient Protected resource API
IKeycloakUserClient Keycloak user API
IKeycloakProtectionClient Authorization server API, used by AddKeycloakAuthorization
// requires confidential client
services.AddKeycloakAdminHttpClient(keycloakOptions);

// based on token forwarding HttpClient middleware and IHttpContextAccessor
services.AddKeycloakProtectionHttpClient(keycloakOptions);

See Keycloak.AuthServices.Sdk - README.md

Build and Development

dotnet cake --target build

dotnet pack -o ./Artefacts

Blog Posts

For more information and real world examples, please see my blog posts related to Keycloak and .NET https://nikiforovall.github.io/tags.html#keycloak-ref

Reference

More Repositories

1

dotfiles

bootstraps dev environment ⚙
Shell
42
star
2

minimal-api-example

Original blog post: https://nikiforovall.github.io/dotnet/aspnetcore/2021/09/10/opinionated-minimal-api.html
C#
39
star
3

dependify

Explore project dependencies in .NET
C#
25
star
4

clean-cli-todo-example

An example of how to use Clean Architecture projects and console (CLI) apps. Based on System.CommandLine. https://github.com/jlevy/the-art-of-command-line https://nikiforovall.github.io/clean-cli-todo-example/
C#
25
star
5

Spectre.Console.Extensions

A library that extends Spectre.Console to build beautiful console apps.
C#
21
star
6

xmindcsharp

XMind API for C#
C#
21
star
7

http-sdk-guide

A comprehensive guide on how to write HTTP Client SDKs in .NET
C#
19
star
8

whats-new-in-dotnet6

A compilation of the latest and greatest additions of .NET 6 and C# 10
C#
12
star
9

na-templates

Event Sourcing, Clean Architecture, and DDD templates
C#
9
star
10

cli-with-spectre-console

An example CLI application based on Spectre.Console
C#
9
star
11

SF-Mapper

A convention-based object-object mapper for SF ☁️
Apex
9
star
12

design-patterns-playground

Examples of GOF patterns. Each pattern has related unit test 📃✔
C#
8
star
13

channels-composition-and-otel

Job Offloading Pattern using an a pipeline built with System.Threading.Channels and OpenTelemetry
C#
7
star
14

aspire-depends-on

Control startup dependencies between Aspire Host Components
C#
7
star
15

social-media-app-aspire

Polyglot persistence via Aspire
C#
6
star
16

azd-webapi

A template of an empty ASP.NET Core Web API (csharp) with Azure Developer CLI (azd)
Bicep
5
star
17

dev-containers

The source repo for my dev-containers definitions
Shell
5
star
18

csharp_workshop

Materials to learn new features of C#8,9.
Jupyter Notebook
5
star
19

intro-to-algorithms

Classical algorithms from Algorithms & DataStructures course based on try-dotnet
C#
5
star
20

docker-for-dotnet-developer

A good starting point for .NET developer to start working on docker on windows/WSL
4
star
21

kiota-getting-started

Kiota + Aspire + .NET 8
C#
4
star
22

tests-instrumentation-with-otel-and-aspire

Integration Tests + Alba + Aspire Dashboard + Testcontainers + Otel
C#
4
star
23

copy-paster

Copy-paste-driven development made easy.
C#
3
star
24

JacobiEigenvalueAlgorithm

Jacobi eigenvalue algorithm openmp implementation. Symmetric eigenvalue problem.
C
3
star
25

NikiforovAll.MassTransit.Dapr

Dapr + Pub/Sub + MassTransit [WIP]
C#
3
star
26

ConfigurationDebugViewEndpoint

Add endpoint-enabled middleware by using IEndpointRouteBuilder extension method. https://nikiforovall.github.io/dotnet/aspnetcore/2021/03/23/endpoint-route-builder-extension-pattern.html
C#
3
star
27

surround-with-csharp

Brings support of surround-with functionality to vscode for C#.
TypeScript
3
star
28

flowable-sdk-dotnet

Flowable API SDK Client for .NET
C#
3
star
29

docker-release-container-sample

Dockerfile
2
star
30

cap-aspire

Aspire + DotNetCore.CAP+ .NET9 + AzureServiceBus + Postgres + Bicep + azd
Bicep
2
star
31

edu-scope-to-mindmap

CLI tool to build mind maps. Developed based on https://nikiforovall.github.io/xmindcsharp/
C#
2
star
32

keycloak-aspire-starter-template

Getting started with Keycloak and Aspire
C#
2
star
33

jmespath-demo

C#
1
star
34

sharepoint-cli

Proof of Concept of SharePoint CLI via Microsoft Graph
C#
1
star
35

openapi-polymorphism

An example of how to serialize model hierarchies in .NET9 Minimal API
C#
1
star
36

devcontainer-for-dotnet6-demo

C#
1
star
37

whats-new-in-dotnet6-vnext

A compilation of the latest and greatest additions of .NET 6 and C# 10
C#
1
star
38

IMEMium

Study portal
TypeScript
1
star
39

nikiforovall.blog.examples

C#
1
star
40

na-ca

Clean Architecture and DDD template
C#
1
star
41

generator-ng-sf

yeoman based generator for angularjs / webpack / es6 / salesforce
JavaScript
1
star
42

xunit-instrumentation-otel-template

Instrument XUnit tests with OpenTelemetry and export results to Aspire Dashboard.
C#
1
star
43

NikiforovAll

1
star
44

aws-batch-dotnet

Learn how to leverage AWS Batch to efficiently process files in S3 using .NET
C#
1
star
45

na-es

Event Sourcing, Clean Architecture, and DDD template
C#
1
star