keycloak-sharp
1.0.4
dotnet add package keycloak-sharp --version 1.0.4
NuGet\Install-Package keycloak-sharp -Version 1.0.4
<PackageReference Include="keycloak-sharp" Version="1.0.4" />
paket add keycloak-sharp --version 1.0.4
#r "nuget: keycloak-sharp, 1.0.4"
// Install keycloak-sharp as a Cake Addin
#addin nuget:?package=keycloak-sharp&version=1.0.4
// Install keycloak-sharp as a Cake Tool
#tool nuget:?package=keycloak-sharp&version=1.0.4
🚧 Project in development.
KeycloakSharp
This project aims to be a guide into how to integrate Keycloak user management into your .NET API project.
1. Key concepts
Controller:
A Controller is a component in your application that handles incoming requests, processes them, and returns an appropriate response. It acts as an intermediary between the user interface and the application's business logic.Endpoint:
An Endpoint is a specific URL or URI (Uniform Resource Identifier) in your application that is used to interact with specific functionalities or resources.Autentication:
Authentication is the process of verifying the identity of users or systems attempting to access a secure environment. It ensures that users are who they claim to be before granting access. Common methods include username/password, tokens, or certificates.Autorization:
Authorization is the process of determining whether an authenticated user or system has the necessary permissions to perform a requested action or access a specific resource. It defines what users are allowed to do within an application or system based on their roles or attributes.
2. Project Configuration
- Create a WebAPI project using .NET 6.
- Install the NuGet package
keycloak-sharp
: [URL]. - Create a new
AuthController
file in theControllers
folder. - Add this code to the created file:
[Route("api/[controller]")] public class AuthController : Controller { private readonly AuthService auth; public AuthController(IConfiguration configuration) { // Get Keycloak configuration from appsettings.json var kcconfig = configuration.GetSection("Keycloak").Get<KeycloakConfig>(); auth = new(kcconfig); } [HttpPost("")] public ActionResult<AuthResponse> Post([FromForm] string grant_type, [FromForm] string? username, [FromForm] string? password, [FromForm] string? refresh_token) { var authReq = new AuthRequest() { GrantType = grant_type, Username = username, Password = password, RefreshToken = refresh_token }; try { var resp = auth.Auth(authReq); return Ok(resp); } catch (Exception) { throw; } } [HttpPost("login")] public IActionResult Login([FromBody] LoginRequest request) { try { return Ok(auth.Login(request)); } catch(Exception) { return StatusCode(500, "Error ocurred logging in"); } } [HttpPost("refresh")] public IActionResult Refresh([FromBody] RefreshRequest request) { try { return Ok(auth.Refresh(request)); } catch (Exception) { return StatusCode(500, "Error ocurred refreshing token"); } } }
- Add Keycloak section to your
appsettings.json
:- Replace
<client_id>
,<client_secret>
,<keycloak_server_url>
and<realm_name>
with your values."Keycloak": { "clientID": "<client_id>", "clientSecret": "<client_secret>", "baseURL": "<keycloak_server_url>", "realm": "<realm_name>", "realmAdminUsername": "", "realmAdminPassword": "" }
- Replace
- Add the following code to the
Program.cs
file before thebuilder.Services.AddControllers()
line:// Configure authentication with Keycloak var kcconfig = builder.Configuration.GetSection("Keycloak").Get<KeycloakConfig>(); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { if (kcconfig.OpenIdConfigURL == null) throw new Exception("No s'ha trobat la configuració OpenID"); options.MetadataAddress = kcconfig.OpenIdConfigURL; options.Authority = kcconfig.RealmURL; options.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidAudience = builder.Configuration["Keycloak:ClientID"], NameClaimType = "preferred_username" }; });
- Add
app.UseAuthentication()
beforeapp.UseAuthorization()
inProgram.cs
;
3. Securing Controllers or Endpoints:
a. Allow only authenticated users
You can enforce authentication either at controller level or at endpoint level.
At controller level:
Place the [Authorize]
attribute just before the class declaration:
[Route("api/[controller]")]
[Authorize]
public class StatusController : Controller
{
// [...]
At endpoint level:
Place the [Authorize]
attribute just before the method declaration:
[Authorize]
[HttpGet("test-authorization")]
public ActionResult<string> GetWithAuthorization()
{
// [...]
(This is equivalent to placing [Authorize]
on all methods of the controller.)
b. Allow only users with certain role
The execution of this method can only be performed for user with 'role1' of the client 'client' OR 'role2'.
[AllowRoles("client@role1","client@role2")]
[HttpGet("test-role")]
public ActionResult<string> GetWithRole()
{
return Ok("Allowed");
}
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
-
net6.0
- Microsoft.AspNetCore.Mvc.Abstractions (>= 2.2.0)
- Microsoft.AspNetCore.Mvc.Core (>= 2.2.5)
- Newtonsoft.Json (>= 13.0.3)
- RestSharp (>= 110.2.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.