Skip to content

horatiu-cod/Keycloak.Net.Authentication

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Keycloak .Net Authentication and Authorization (UMA)

Build Build

Authentication and Authorization with Keycloak in .NET and ASP.NET Core. Secure your api with Keycloak UMA authorization and JWT bearer authentication.

Add the Keycloak.Net.Authentification and Keycloak.Net.Authorization nuget packages to your project.

Api calls requires auhorization header with an JWT token from Keycloak.

POST https://yourapi/action HTTP/1.1
Auhorization: Bearer JwtTokenContent

How to use

Authentication

Add to program.cs of your api

Option no.1 (easiest way)

using Keycloak.Net.Authentication;
using Keycloak.Net.Authorization;
new code πŸ‘†

.
builder.Services
  .AddKeyCloakAuthentication()
  .AddKeyCloakJwtBearerOptions("appsettings_section_name");
.....
app.UseAuthentication();
app.UseAuthorization();

Add section to the appsettings.{Environment}.json

  • Authority is required. If not set will throw exception during app startup.
  • Set the audience as "Audience", "ValidAudience" or "ValidAudiences". If not set will throw exception during app startup.
 {
    "KeycloakUrl": "<<FROM_USER_SECRET>>",
    "RealmName": "<<FROM_USER_SECRET>>",
    
    "appsettings_section_name": {
          "Authority": "{KeycloakUrl}{RealmName}",
          "Audience": "<<Audience>>"
       }
// or
    "appsettings_section_name": {
          "Authority": "{KeycloakUrl}{RealmName}",
          "ValidAudience": "<<Audience>>"
       }
//or
    "appsettings_section_name": {
          "Authority": "{KeycloakUrl}{RealmName}",
          "ValidAudiences": ["<<Audience>>"]
       }
 }

Option no.2

  • Variation of first option. Additional configuration of JwtBearerOptions available.
  • If set will override the value of same property defined in appsettings.{Environment}.json
builder.Services
  .AddKeyCloakAuthentication()
  .AddKeyCloakJwtBearerOptions("appsettings_section_name", options =>
  {
    options.Audience = "<<Audience>>";
    options.SaveToken = true;

    options.TokenValidationParameters.ClockSkew = TimeSpan.FromSeconds(30);
  });

Option no.3

  • If you want to get auth options from other source, not from appsettings.{Environment}.json, you can pass Action<JwtBearerValidationOptions> instead.
  • Authority is required. If not set will throw exception during app startup.
  • Set the audience as "Audience", "ValidAudience" or "ValidAudiences".If not set will throw exception during app startup.
builder.Services
  .AddKeyCloakAuthentication()
  .AddKeyCloakJwtBearerOptions(options =>
    {
        options.KeycloakAuthority = "https://{host}/realms/{realm}";
        options.KeycloakAudience = "<<Audience>>";
    })

Option no.4

  • You have to manually configure the JwtBearerOtions.
builder.Services
  .AddKeyCloakAuthentication()
  .AddJwtBearerOptions(options =>
    {
        options.Authority = "https://{host}/realms/{realm}";
        options.Audience = "<<Audience>>";
        ......
        options.TokenValidationParameters = new TokenValidationParameters( options =>
        {
          options.ClockSkew = TimeSpan.FromSeconds(30);
          .......
        });
    });

JWT transformation

  • Under the hood the Keyclaok JWT is mapped and transformed to Identity JWT
  • The Keycloak Realm and Client "roles" claims are mapped and transformed to ClaimType.Role
  • By default the Keycloak "preferred_username" claim is transformed to ClaimType.Name. You can change it by just adding the following:
{
    "KeycloakUrl": "<<FROM_USER_SECRET>>",
    "RealmName": "<<FROM_USER_SECRET>>",
    
    "appsettings_section_name": {
          "Authority": "{KeycloakUrl}{RealmName}",
          "Audience": "<<Audience>>",
          "NameClaim: "<<NameOfClaimWhichShouldBeSetToNameClaim>>"
       }
}

Authorization

Add to program.cs of your api

using Keycloak.Net.Authentication;
using Keycloak.Net.Authorization;
new code πŸ‘†

.....
πŸ‘‡new code
builder.Services
  // Keycloak.Net.Authentication services 
  .AddKeyCloakAuthentication()
  .AddKeyCloakJwtBearerOptions("appsettings_section_name");
.....
app.UseAuthentication();
app.UseAuthorization();

Add and configure Keycloak.Net.Authorization

Configure using the Action<ClientConfiguration>

builder.Services
  // Keycloak.Net.Authentication services 
  .AddKeyCloakAuthentication()
  .AddKeyCloakJwtBearerOptions("appsettings_section_name");
  .AddUma(client =>
    {
        client.ClientId = "client-role";
    });
new code πŸ‘†
.....
πŸ‘‡new code 
app.UseUma();

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

Configure by appsettings.{Environment}.json

builder.Services
  // Keycloak.Net.Authentication services 
  .AddKeyCloakAuthentication()
  .AddKeyCloakJwtBearerOptions("Appsettings_Section_Name")
  .AddUma("Client_Section_Name);
new code πŸ‘†
.....

πŸ‘‡new code 
app.UseUma();

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

Add to your appsettings.{Environment}.json

{
 "Client_Section_Name": {
   "ClientId": "<CLIENT_NAME>"
}

Extra AuthorizationOptions configuration can be added

.AddUma("Client", configure =>
{
    configure.AddPolicy("<<policy_name>>", configure =>
    {
        configure.RequireClaim("<<claim_name>>", "<<claim_value>>");
    });
    configure.AddPolicy("<<policy_name>>", policy =>
    {
        policy.RequireUserName("<<username>>");
    });
    configure.AddPolicy("<<policy_name>>", policy =>
    {
        policy.RequireAuthenticatedUser();
    });
    configure.AddPolicy("<<policy_name>>", policy =>
    {
        policy.RequireRole("<<role_name>>");
    });
})

Add to your endpoints

MinimalAPI

Via custom extenxion method

app.MapGet("api/example", () =>
    Results.Ok()
    .RequireUmaAuthorization(resource: "<<resource>>", scope: "<<scope>>");

Via Attribute

app.MapGet("api/example", [Permission(Resource = "<<resource>>", Scope = "<<scope>>")] () =>
    Results.Ok();

Via ASP.NET extension method. The policy string format is: Permission:<>,<>

app.MapGet("api/example", () =>
    Results.Ok()
    .RequireAuthorization("Permission:<<resource>>,<<scope>>");

How it works

The UseUMA middleware exchange the JWT of the request with a RPT received from Keycloak auth server after validating the realm access permission. The RPT contains the permission granted by the auth server, and is used to autorize access of the resources.

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages