- Notifications
You must be signed in to change notification settings - Fork126
Authentication and Authorization with Keycloak and ASP.NET Core 🔐
License
NikiforovAll/keycloak-authorization-services-dotnet
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
🔐 Easy Authentication and Authorization with Keycloak in .NET.
For Developer Documentation see:https://nikiforovall.github.io/keycloak-authorization-services-dotnet
See:https://nikiforovall.github.io/keycloak-authorization-services-dotnet-docs
Install packages:
dotnet add package Keycloak.AuthServices.Authentication
// Program.csusingKeycloak.AuthServices.Authentication;varbuilder=WebApplication.CreateBuilder(args);builder.Services.AddKeycloakWebApiAuthentication(builder.Configuration);builder.Services.AddAuthorization();varapp=builder.Build();app.UseAuthentication();app.UseAuthorization();app.MapGet("/",()=>"Hello World!").RequireAuthorization();app.Run();
In this example, configuration is based onappsettings.json
.
//appsettings.json{"Keycloak": {"realm":"Test","auth-server-url":"http://localhost:8080/","ssl-required":"none","resource":"test-client","verify-token-audience":false,"credentials": {"secret":"" },"confidential-port":0 }}
WithKeycloak.AuthServices.Authorization
, you can implement role-based authorization in your application. This package allows you to define policies based on roles. Also, you can use Keycloak as Authorization Server. It is a powerful way to organize and apply authorization polices centrally.
varbuilder=WebApplication.CreateBuilder(args);varhost=builder.Host;varconfiguration=builder.Configuration;varservices=builder.Services;services.AddKeycloakWebApiAuthentication(configuration);services.AddAuthorization(options=>{options.AddPolicy("AdminAndUser", builder=>{builder.RequireRealmRoles("User")// Realm role is fetched from token.RequireResourceRoles("Admin");// Resource/Client role is fetched from token});}).AddKeycloakAuthorization(configuration);varapp=builder.Build();app.UseAuthentication();app.UseAuthorization();app.MapGet("/hello",()=>"[]").RequireAuthorization("AdminAndUser");app.Run();
varservices=newServiceCollection();services.AddKeycloakAdminHttpClient(newKeycloakAdminClientOptions{AuthServerUrl="http://localhost:8080/",Realm="master",Resource="admin-api",});varsp=services.BuildServiceProvider();varclient=sp.GetRequiredService<IKeycloakRealmClient>();varrealm=awaitclient.GetRealmAsync("Test");
dotnet cake --target build
dotnet cake --target test
dotnet pack -o ./Artefacts
About
Authentication and Authorization with Keycloak and ASP.NET Core 🔐
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.