How-to Guide: Common Tasks with TideCloak in CSharp
Install packages
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
dotnet add package Microsoft.AspNetCore.Authentication.Cookies
# Optional (APIs)
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Minimal Program.cs (web app)
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
var b = WebApplication.CreateBuilder(args);
b.WebHost.UseUrls("http://localhost:8000");
b.Services.AddRazorPages();
b.Services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(o =>
{
o.Authority = "http://localhost:8080/realms/myrealm";
o.ClientId = "myclient";
o.ResponseType = OpenIdConnectResponseType.Code;
o.RequireHttpsMetadata = false; // dev only
o.SaveTokens = true;
o.Scope.Add("openid");
o.Scope.Add("profile");
});
var app = b.Build();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
Trigger login/logout
// Login:
return Challenge(new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectDefaults.AuthenticationScheme);
// Logout:
return SignOut(new AuthenticationProperties { RedirectUri = "/" },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
Show user claims in a page
@if (User.Identity?.IsAuthenticated ?? false)
{
<p><b>User:</b> @User.Identity!.Name</p>
<p><b>Email:</b> @User.FindFirst("email")?.Value</p>
<p><b>Subject:</b> @User.FindFirst("sub")?.Value</p>
}
Require auth / roles
// Program.cs
builder.Services.AddAuthorization(o =>
{
o.AddPolicy("AdminsOnly", p => p.RequireRole("admin"));
});
// Controller/Page
[Authorize] // or [Authorize(Policy="AdminsOnly")]
public class DashboardModel : PageModel { /* ... */ }
If your roles are nested inside
realm_access
/resource_access
, map them during auth or in a custom claims transformation.
Protect API endpoints with JWT Bearer
builder.Services.AddAuthentication()
.AddJwtBearer("bearer", o =>
{
o.Authority = "http://localhost:8080/realms/myrealm";
o.Audience = "myclient";
o.RequireHttpsMetadata = false;
});
app.MapGet("/api/me",
[Authorize(AuthenticationSchemes="bearer")] (ClaimsPrincipal user) =>
Results.Ok(new { sub = user.FindFirst("sub")?.Value })
);
IIS hosting (checklist)
- Install ASP.NET Core Hosting Bundle
dotnet publish -c Release
- Point IIS site/app to publish folder
- If combined with WebForms, configure Core as sub‑application and ensure ports/paths match the OIDC redirect URIs
Useful URLs (Keycloak/TideCloak)
- Registration:
/realms/{realm}/protocol/openid-connect/registrations
- Account:
/realms/{realm}/account
- JWKs:
/.well-known/openid-configuration
→jwks_uri