Configure Authentication
Keycloak.AuthServices.Authentication provides robust authentication mechanisms for both web APIs and web applications. For web APIs, it supports JWT Bearer token authentication, which allows clients to authenticate to the API by providing a JWT token in the Authorization header of their requests. For web applications, it supports OpenID Connect, a simple identity layer on top of the OAuth 2.0 protocol
Table of Contents:
Web API
Here is what library does for you:
- Adds and configures
AddJwtBearer
based on provided configuration. - Registers
IOptions<KeycloakAuthenticationOptions>
andIOptions<JwtBearerOptions>
.
ServiceCollection Extensions
The Keycloak.AuthServices.Authentication library will automatically retrieve the configuration values under the "Keycloak" section. You can access these values in your code to configure the authentication process. This section is likely defined in your application's configuration file, such as appsettings.json
{
"Keycloak": {
"realm": "Test",
"auth-server-url": "http://localhost:8080/",
"ssl-required": "none",
"resource": "test-client",
"verify-token-audience": false,
"credentials": {
"secret": ""
}
}
}
Simply add:
services.AddKeycloakWebApiAuthentication(configuration);
This default assumption of the "Keycloak" section allows you to easily configure the library without explicitly specifying the section name every time. However, if you have a different section name or want to customize the configuration retrieval process, the library provides additional methods and options to handle that.
services.AddKeycloakWebApiAuthentication(
configuration.GetSection(KeycloakAuthenticationOptions.Section)
);
services.AddKeycloakWebApiAuthentication(
configuration,
KeycloakAuthenticationOptions.Section
);
Not everything you want to do can be configured with KeycloakAuthenticationOptions
, for more fine-grained configuration use next method overload that takes Action<JwtBearerOptions>
:
services.AddKeycloakWebApiAuthentication(
configuration,
(options) =>
{
options.RequireHttpsMetadata = false;
options.Audience = "test-client";
}
);
NOTE
KeycloakAuthenticationOptions
("Keycloak") takes precedence over Authentication:Schemes:{SchemeName}
("Bearer" - JwtBearerOptions
) in the case of default configuration
Here is a trick to bind options from configuration an override directly in the same code:
services.AddKeycloakWebApiAuthentication(options =>
{
configuration.BindKeycloakOptions(options);
options.SslRequired = "none";
options.Audience = "test-client";
});
Typically, ASP.NET Core expects to find these (default) options under the Authentication:Schemes:{SchemeName}
. See Configuring Authentication Strategies for more details. Here is how to configure JwtBearerOptions:
services.AddKeycloakWebApiAuthentication(configuration);
{
"Keycloak": {
"ssl-required": "internal",
"resource": "test-client",
"verify-token-audience": true,
"credentials": {
"secret": "Tgx4lvbyhho7oNFmiIupDRVA8ioQY7PW"
},
"confidential-port": 0
},
"Authentication": {
"DefaultScheme": "Bearer",
"Schemes": {
"Bearer": {
"ValidAudiences": [
"default-test-client-new"
],
"RequireHttpsMetadata": true,
"Authority": "http://localhost:8080/realms/DefaultTest",
"TokenValidationParameters": {
"ValidateAudience": false
}
}
}
}
}
AuthenticationBuilder Extensions
For situations when you want to override Authentication Scheme or you just prefer more verbose way of defining your project's Authentication you can use AuthenticationBuilder
extension methods:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddKeycloakWebApi(configuration);
Use IConfigurationSection
:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddKeycloakWebApi(configuration.GetSection(KeycloakAuthenticationOptions.Section));
Inline declaration:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddKeycloakWebApi(options =>
{
options.Resource = "test-client";
options.Realm = "Test";
options.SslRequired = "none";
options.AuthServerUrl = "http://localhost:8080/";
options.VerifyTokenAudience = false;
});
Inline declaration with JwtBearerOptions
overrides:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddKeycloakWebApi(
options =>
{
options.Resource = "test-client";
options.Realm = "Test";
options.AuthServerUrl = "http://localhost:8080/";
options.VerifyTokenAudience = false;
},
options =>
{
options.RequireHttpsMetadata = false;
options.Audience = "test-client";
}
);
Web App beta
In the context of web development, a web application (web app) refers to a software application that runs on a web server and is accessed by users through a web browser.
OpenID Connect (OIDC) is a protocol that allows web applications to authenticate and authorize users. It is built on top of the OAuth 2.0 protocol, which is a widely used authorization framework. OIDC adds an identity layer to OAuth 2.0, enabling web apps to obtain information about the authenticated user.
Here is what library does for you:
- Adds and configures
OpenIdConnect
based on provided configuration. - Registers
IOptions<KeycloakAuthenticationOptions>
,IOptions<OpenIdConnectOptions>
, andIOptions<CookieAuthenticationOptions>
.
ServiceCollection Extensions 🚧
From configuration:
public static KeycloakWebAppAuthenticationBuilder AddKeycloakWebAppAuthentication(
this IServiceCollection services,
IConfiguration configuration,
string configSectionName = KeycloakAuthenticationOptions.Section,
string openIdConnectScheme = OpenIdConnectDefaults.AuthenticationScheme,
string cookieScheme = CookieAuthenticationDefaults.AuthenticationScheme,
string? displayName = null
)
AuthenticationBuilder Extensions 🚧
From configuration:
public static KeycloakWebAppAuthenticationBuilder AddKeycloakWebApp(
this AuthenticationBuilder builder,
IConfiguration configuration,
string configSectionName = KeycloakAuthenticationOptions.Section,
string openIdConnectScheme = OpenIdConnectDefaults.AuthenticationScheme,
string cookieScheme = CookieAuthenticationDefaults.AuthenticationScheme,
string? displayName = null
)
Inline:
public static KeycloakWebAppAuthenticationBuilder AddKeycloakWebApp(
this AuthenticationBuilder builder,
Action<KeycloakAuthenticationOptions> configureKeycloakOptions,
Action<CookieAuthenticationOptions>? configureCookieAuthenticationOptions = null,
Action<OpenIdConnectOptions>? configureOpenIdConnectOptions = null,
string openIdConnectScheme = OpenIdConnectDefaults.AuthenticationScheme,
string? cookieScheme = CookieAuthenticationDefaults.AuthenticationScheme,
string? displayName = null
)
See source code for more details.
TIP
See an example of how to use AddKeycloakWebApp
in MVC application - Web App MVC
Adapter File Configuration Provider
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.
var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureKeycloakConfigurationSource("keycloak.json");
builder.Services.AddKeycloakWebApiAuthentication(builder.Configuration);
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", () => "Hello World!").RequireAuthorization();
app.Run();
Here is an example of keycloak.json adapter file:
{
"realm": "Test",
"auth-server-url": "http://localhost:8088/",
"ssl-required": "external",
"resource": "test-client",
"verify-token-audience": true
}