Search code examples
c#authenticationkeycloakopenid-connectasp.net-core-8

ASP.NET Core 8 Blazor : OpenIdConnect save user scope to app database


For testing and fun, I created a default ASP.NET Core 8 Blazor web app with individual accounts for authentication, and I added my keycloak to it. In keycloak, users can have custom attributes, like where they work (cegnev). How can I make that my ASP.NET Core app saves that data to its database?

This is my modified ApplicationUser:

using Microsoft.AspNetCore.Identity;

namespace TesztBlazorAuth.Data
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        public string cegnev { get; set; }
    }
}

Program.cs:

using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using TesztBlazorAuth.Components;
using TesztBlazorAuth.Components.Account;
using TesztBlazorAuth.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;

// Add services to the container.
builder.Services.AddRazorComponents()
       .AddInteractiveServerComponents();

builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders();

builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();

builder.Services.AddAuthentication()
.AddGoogle(options =>
{
    options.ClientId = configuration["GoogleAuth:id"];
    options.ClientSecret = configuration["GoogleAuth:secret"];
})
.AddOpenIdConnect("Keycloak", "CorpAuth", options =>
{
    options.Authority = $"{configuration["Keycloak:auth-server-url"]}realms/{configuration["Keycloak:realm"]}";
    options.ClientId = configuration["Keycloak:resource"];
    options.ClientSecret = configuration["Keycloak:credentials:secret"];
    options.ResponseType = "code";
    options.SaveTokens = true;

    options.TokenValidationParameters = new TokenValidationParameters
       {
           ValidateIssuer = true
       };
    
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
    options.Scope.Add("phone");
    options.Scope.Add("cegnev");
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorComponents<App>()
       .AddInteractiveServerRenderMode();

// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();
app.UseAntiforgery();
app.Run();

The users should have the cegnev from keyclaok in the database.


Solution

  • This is what works for me, is there any more simple way?:

    .AddOpenIdConnect("Keycloak", "CorpAuth", options =>
    {
        options.Authority = $"{configuration["Keycloak:auth-server-url"]}realms/{configuration["Keycloak:realm"]}";
        options.ClientId = configuration["Keycloak:resource"];
        options.ClientSecret = configuration["Keycloak:credentials:secret"];
        options.ResponseType = "code";
        options.SaveTokens = true;
    
        options.TokenValidationParameters = new TokenValidationParameters
           {
               ValidateIssuer = true
           };
    
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.Scope.Add("email");
        options.Scope.Add("phone");
        options.Scope.Add("cegnev");
    
        options.ClaimActions.MapJsonKey("cegnev", "cegnev");
    
        options.Events = new OpenIdConnectEvents
        {
            OnTokenValidated = async context =>
            {
                var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
                var userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
                var signInManager = context.HttpContext.RequestServices.GetRequiredService<SignInManager<ApplicationUser>>();
    
                var email = claimsIdentity.FindFirst(ClaimTypes.Email)?.Value;
                var user = await userManager.FindByEmailAsync(email);
    
                if (user == null)
                {
                    user = new ApplicationUser
                    {
                        UserName = email,
                        Email = email,
                        cegnev = claimsIdentity.FindFirst("cegnev")?.Value
                    };
    
                    var result = await userManager.CreateAsync(user);
                    if (result.Succeeded)
                    {
                        await signInManager.SignInAsync(user, isPersistent: false);
                    }
                }
                else
                {
                    var cegnevClaim = claimsIdentity.FindFirst("cegnev")?.Value;
                    if (!string.IsNullOrEmpty(cegnevClaim) && user.cegnev != cegnevClaim)
                    {
                        user.cegnev = cegnevClaim;
                        await userManager.UpdateAsync(user);
                    }
                }
            }
        };
    });