feat(security): merge DB-backed LDAP role grants into login claims

This commit is contained in:
Joseph Doherty
2026-05-29 09:51:22 -04:00
parent 042f3b6a65
commit f210f09caf
2 changed files with 134 additions and 1 deletions
@@ -6,6 +6,9 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Configuration.Services;
using ZB.MOM.WW.OtOpcUa.Security.Jwt;
using ZB.MOM.WW.OtOpcUa.Security.Ldap;
@@ -40,6 +43,7 @@ public static class AuthEndpoints
private static async Task<IResult> LoginAsync(
HttpContext http,
ILdapAuthService ldap,
ILdapGroupRoleMappingService roleMappings,
CancellationToken ct)
{
var isForm = http.Request.HasFormContentType;
@@ -83,13 +87,27 @@ public static class AuthEndpoints
return Results.Redirect("/login" + qs);
}
IReadOnlyList<string> roles = result.Roles;
try
{
var dbRows = await roleMappings.GetByGroupsAsync(result.Groups, ct);
roles = RoleMapper.Merge(result.Roles, dbRows);
}
catch (Exception ex)
{
// A DB hiccup must never block sign-in — fall back to the appsettings baseline roles.
http.RequestServices.GetService<ILoggerFactory>()?
.CreateLogger("ZB.MOM.WW.OtOpcUa.Security.AuthEndpoints")
.LogWarning(ex, "DB role-map lookup failed for {User}; using appsettings baseline roles", username);
}
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, result.Username ?? username),
new(JwtTokenService.UsernameClaimType, result.Username ?? username),
new(JwtTokenService.DisplayNameClaimType, result.DisplayName ?? username),
};
foreach (var role in result.Roles)
foreach (var role in roles)
claims.Add(new Claim(ClaimTypes.Role, role));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);