Skip to content

Instantly share code, notes, and snippets.

@Szer
Created June 1, 2024 08:51
Show Gist options
  • Save Szer/a2415de8fd71a9aecfa9a63dd71b6c07 to your computer and use it in GitHub Desktop.
Save Szer/a2415de8fd71a9aecfa9a63dd71b6c07 to your computer and use it in GitHub Desktop.
keycloak example

docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:24.0.4 start-dev

  1. Create confidential client test (no special settings)
  2. Create public client front (no special settings)
  3. Create user in KC with username abc and set NON TEMPORARY password for him abc
  4. Get KC token
curl --request POST \
  --url http://localhost:8080/realms/master/protocol/openid-connect/token \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data client_id=front \
  --data username=abc \
  --data password=abc \
  --data grant_type=password
  1. Try API
curl --request GET \
  --url http://localhost:5236/ \
  --header 'Authorization: Bearer TAKE_ACCESS_TOKEN_FROM_ABOVE'
  1. Response: Hello abc!
{
"Keycloak": {
"realm": "master",
"auth-server-url": "http://localhost:8080/",
"ssl-required": "none",
"resource": "test",
"verify-token-audience": false,
"credentials": {
"secret": "BuIpbumh0dAX8oaRP83MctDtIXQk28GC"
},
"confidential-port": 0
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Keycloak.AuthServices.Authentication" Version="2.4.1" />
<PackageReference Include="Keycloak.AuthServices.Common" Version="2.4.1" />
</ItemGroup>
</Project>
using System.Security.Claims;
using Keycloak.AuthServices.Authentication;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeycloakWebApiAuthentication(builder.Configuration);
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", (ClaimsPrincipal user) => $"Hello {user.Identity!.Name}!").RequireAuthorization();
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment