.netasp.net-corekeycloak

Migrate keycloak 1.5.2 to 2.5.3 in .NET Core


I had created a Poc with 1.5.2 version and everything was working fine, but after updating to v2.5.3, my keycloak implementation broke.

https://github.com/user-attachments/assets/73c614d1-8306-4f2f-a7c2-b0670472a640

1.5.2 class Program.cs:

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

builder.Services.AddKeycloakAuthentication(authenticationOptions);


var authorizationOptions = builder
                            .Configuration
                            .GetSection(KeycloakProtectionClientOptions.Section)
                            .Get<KeycloakProtectionClientOptions>();

builder.Services.AddKeycloakAuthorization(authorizationOptions);

2.5.3 Program.cs & Controller:

builder.Services.AddKeycloakWebApiAuthentication(builder.Configuration);
builder.Services.AddKeycloakAuthorization(builder.Configuration);

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{

    [Route("read")]
    [HttpGet]
    [Authorize(Roles = "Read")]
    public async Task<IActionResult> Read()
    {
        return Ok(Names());
    }
}

https://github.com/user-attachments/assets/f0455b0e-5789-4824-a9f5-b6ba5dca5f7b https://github.com/user-attachments/assets/7049a579-c83d-4262-8fd3-55b3b93a7f3d

In 2.5.3 now, even i have all roles in token return 401 or 403.


Solution

  • If you are developing an API, for authentication, you should use:

    builder.Services.AddKeycloakWebApiAuthentication(builder.Configuration);

    For a web app, use:

    builder.Services.AddKeycloakWebAppAuthentication(builder.Configuration);

    For authorization, use:

    builder.Services.AddKeycloakAuthorization().AddAuthorizationServer(builder.Configuration);

    You can follow the migration guide below:

    Source:https://nikiforovall.github.io/keycloak-authorization-services-dotnet/migration.html