Enrich AD users from SGU profile metadata
This commit is contained in:
@@ -36,6 +36,27 @@ public sealed class BrokerOptions
|
||||
throw new InvalidOperationException("NTLM timeout or redirect limits are outside the supported range.");
|
||||
}
|
||||
|
||||
if (Ntlm.MaxProfileBytes is < 32 * 1024 or > 2 * 1024 * 1024)
|
||||
{
|
||||
throw new InvalidOperationException("The SGU profile response limit is outside the supported range.");
|
||||
}
|
||||
|
||||
foreach (string profilePath in new[] { Ntlm.AdministrativeProfilePath, Ntlm.MenuProfilePath })
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(profilePath))
|
||||
{
|
||||
throw new InvalidOperationException("SGU profile paths are required.");
|
||||
}
|
||||
|
||||
Uri profileUri = new(endpoint, profilePath);
|
||||
if (profileUri.Scheme != Uri.UriSchemeHttps ||
|
||||
!string.IsNullOrEmpty(profileUri.UserInfo) ||
|
||||
!Ntlm.AllowedRedirectHosts.Contains(profileUri.IdnHost, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new InvalidOperationException("SGU profile paths must resolve to an allowed HTTPS host.");
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(Directory.LdapHost) ||
|
||||
string.IsNullOrWhiteSpace(Directory.BaseDn) ||
|
||||
string.IsNullOrWhiteSpace(Directory.DomainNetbios) ||
|
||||
@@ -83,6 +104,13 @@ public sealed class NtlmOptions
|
||||
|
||||
public int MaxRedirects { get; init; } = 5;
|
||||
|
||||
public string AdministrativeProfilePath { get; init; } =
|
||||
"/psulsa/gadmon/capitalhumano/controlincidencias/incidencias.aspx";
|
||||
|
||||
public string MenuProfilePath { get; init; } = "/psulsa/menu.aspx";
|
||||
|
||||
public int MaxProfileBytes { get; init; } = 512 * 1024;
|
||||
|
||||
public string[] AllowedRedirectHosts { get; init; } = ["sgu.ulsa.edu.mx"];
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Collections.Concurrent;
|
||||
using System.DirectoryServices;
|
||||
using SGU.AuthBroker.Core.Directory;
|
||||
using SGU.AuthBroker.Core.Identity;
|
||||
using SGU.AuthBroker.Core.Profiles;
|
||||
using SGU.AuthBroker.Options;
|
||||
|
||||
namespace SGU.AuthBroker.Services;
|
||||
@@ -19,6 +20,7 @@ public sealed class ActiveDirectorySynchronizer(BrokerOptions options) : IActive
|
||||
|
||||
public async Task<DirectorySyncResult> SynchronizeAsync(
|
||||
UserIdentity identity,
|
||||
InstitutionalProfile? profile,
|
||||
string password,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -27,7 +29,7 @@ public sealed class ActiveDirectorySynchronizer(BrokerOptions options) : IActive
|
||||
try
|
||||
{
|
||||
return await Task.Run(
|
||||
() => Synchronize(identity, password),
|
||||
() => Synchronize(identity, profile, password),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
@@ -40,7 +42,10 @@ public sealed class ActiveDirectorySynchronizer(BrokerOptions options) : IActive
|
||||
}
|
||||
}
|
||||
|
||||
private DirectorySyncResult Synchronize(UserIdentity identity, string password)
|
||||
private DirectorySyncResult Synchronize(
|
||||
UserIdentity identity,
|
||||
InstitutionalProfile? profile,
|
||||
string password)
|
||||
{
|
||||
string targetOuDn = options.GetOuDn(identity.Role);
|
||||
using DirectoryEntry root = Bind(options.BaseDn);
|
||||
@@ -95,6 +100,8 @@ public sealed class ActiveDirectorySynchronizer(BrokerOptions options) : IActive
|
||||
user.Properties["pwdLastSet"].Value = -1;
|
||||
user.CommitChanges();
|
||||
|
||||
TryApplyProfile(user, identity, profile);
|
||||
|
||||
return new DirectorySyncResult(
|
||||
options.DomainNetbios,
|
||||
identity.UserName,
|
||||
@@ -108,6 +115,54 @@ public sealed class ActiveDirectorySynchronizer(BrokerOptions options) : IActive
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryApplyProfile(
|
||||
DirectoryEntry user,
|
||||
UserIdentity identity,
|
||||
InstitutionalProfile? profile)
|
||||
{
|
||||
if (profile is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
SetOptionalProperty(user, "displayName", profile.DisplayName);
|
||||
SetOptionalProperty(user, "mail", profile.Email);
|
||||
SetOptionalProperty(user, "title", profile.JobTitle);
|
||||
SetOptionalProperty(user, "department", profile.Department);
|
||||
SetOptionalProperty(user, "employeeType", profile.EmployeeType);
|
||||
if (string.Equals(profile.EmployeeNumber, identity.NumericId, StringComparison.Ordinal))
|
||||
{
|
||||
SetOptionalProperty(user, "employeeID", profile.EmployeeNumber);
|
||||
}
|
||||
|
||||
user.CommitChanges();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Metadata is intentionally best-effort. User creation, password sync,
|
||||
// and account enablement have already committed successfully.
|
||||
try
|
||||
{
|
||||
user.RefreshCache();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Discarding the optional property cache must not alter the
|
||||
// already committed password synchronization result.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetOptionalProperty(DirectoryEntry entry, string propertyName, string? value)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
entry.Properties[propertyName].Value = value;
|
||||
}
|
||||
}
|
||||
|
||||
private DirectoryEntry BindOrCreateOu(string ouDn, DirectoryEntry root)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using SGU.AuthBroker.Core.Authentication;
|
||||
using SGU.AuthBroker.Core.Identity;
|
||||
using SGU.AuthBroker.Core.Profiles;
|
||||
using SGU.AuthBroker.Options;
|
||||
|
||||
namespace SGU.AuthBroker.Services;
|
||||
@@ -9,29 +12,31 @@ public sealed class NtlmCredentialValidator(BrokerOptions options) : INtlmCreden
|
||||
private readonly NtlmOptions options = options.Ntlm;
|
||||
|
||||
public async Task<NtlmValidationResult> ValidateAsync(
|
||||
string userName,
|
||||
UserIdentity identity,
|
||||
string password,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Uri current = new(this.options.Endpoint, UriKind.Absolute);
|
||||
Uri current = GetProfileUri(identity.Role);
|
||||
HashSet<string> allowedHosts = new(
|
||||
this.options.AllowedRedirectHosts,
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
NetworkCredential credential = new(userName, password, this.options.Domain);
|
||||
NetworkCredential credential = new(identity.UserName, password, this.options.Domain);
|
||||
CredentialCache credentialCache = new();
|
||||
HashSet<string> credentialedAuthorities = new(StringComparer.OrdinalIgnoreCase);
|
||||
CookieContainer cookieContainer = new();
|
||||
|
||||
using HttpClientHandler handler = new()
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
AutomaticDecompression = DecompressionMethods.All,
|
||||
CheckCertificateRevocationList = true,
|
||||
CookieContainer = cookieContainer,
|
||||
Credentials = credentialCache,
|
||||
MaxConnectionsPerServer = 4,
|
||||
MaxResponseHeadersLength = 64,
|
||||
PreAuthenticate = false,
|
||||
UseCookies = false,
|
||||
UseCookies = true,
|
||||
UseDefaultCredentials = false,
|
||||
UseProxy = false
|
||||
};
|
||||
@@ -104,9 +109,17 @@ public sealed class NtlmCredentialValidator(BrokerOptions options) : INtlmCreden
|
||||
continue;
|
||||
}
|
||||
|
||||
return statusCode is >= 200 and < 300
|
||||
? NtlmValidationResult.Valid()
|
||||
: NtlmValidationResult.Invalid();
|
||||
if (statusCode is >= 200 and < 300)
|
||||
{
|
||||
InstitutionalProfile? profile = await TryReadProfileAsync(
|
||||
response,
|
||||
identity,
|
||||
timeout.Token,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return NtlmValidationResult.Valid(profile);
|
||||
}
|
||||
|
||||
return NtlmValidationResult.Invalid();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +131,93 @@ public sealed class NtlmCredentialValidator(BrokerOptions options) : INtlmCreden
|
||||
}
|
||||
}
|
||||
|
||||
private Uri GetProfileUri(InstitutionalRole role)
|
||||
{
|
||||
Uri endpoint = new(options.Endpoint, UriKind.Absolute);
|
||||
string path = role == InstitutionalRole.Administrative
|
||||
? options.AdministrativeProfilePath
|
||||
: options.MenuProfilePath;
|
||||
return new Uri(endpoint, path);
|
||||
}
|
||||
|
||||
private async Task<InstitutionalProfile?> TryReadProfileAsync(
|
||||
HttpResponseMessage response,
|
||||
UserIdentity identity,
|
||||
CancellationToken timeoutToken,
|
||||
CancellationToken requestCancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
string html = await ReadLimitedStringAsync(
|
||||
response.Content,
|
||||
options.MaxProfileBytes,
|
||||
timeoutToken).ConfigureAwait(false);
|
||||
return identity.Role == InstitutionalRole.Administrative
|
||||
? SguProfileParser.ParseAdministrative(html, identity.NumericId) ??
|
||||
SguProfileParser.ParseMenu(html)
|
||||
: SguProfileParser.ParseMenu(html);
|
||||
}
|
||||
catch (OperationCanceledException) when (requestCancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Profile enrichment is optional. A successful NTLM response must still
|
||||
// synchronize the exact password even if SGU changes its presentation HTML.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> ReadLimitedStringAsync(
|
||||
HttpContent content,
|
||||
int maximumBytes,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (content.Headers.ContentLength is long contentLength && contentLength > maximumBytes)
|
||||
{
|
||||
throw new InvalidDataException("The SGU profile response exceeded the configured limit.");
|
||||
}
|
||||
|
||||
await using Stream stream = await content
|
||||
.ReadAsStreamAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
using MemoryStream buffer = new(Math.Min(maximumBytes, 64 * 1024));
|
||||
byte[] chunk = new byte[8192];
|
||||
while (true)
|
||||
{
|
||||
int read = await stream
|
||||
.ReadAsync(chunk.AsMemory(), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (buffer.Length + read > maximumBytes)
|
||||
{
|
||||
throw new InvalidDataException("The SGU profile response exceeded the configured limit.");
|
||||
}
|
||||
|
||||
buffer.Write(chunk, 0, read);
|
||||
}
|
||||
|
||||
string? charset = content.Headers.ContentType?.CharSet?.Trim('"', '\'');
|
||||
Encoding encoding;
|
||||
try
|
||||
{
|
||||
encoding = string.IsNullOrWhiteSpace(charset)
|
||||
? Encoding.UTF8
|
||||
: Encoding.GetEncoding(charset);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
encoding = Encoding.UTF8;
|
||||
}
|
||||
|
||||
return encoding.GetString(buffer.GetBuffer(), 0, checked((int)buffer.Length));
|
||||
}
|
||||
|
||||
private static bool IsAllowedHttpsUri(Uri uri, HashSet<string> allowedHosts) =>
|
||||
uri.Scheme == Uri.UriSchemeHttps &&
|
||||
string.IsNullOrEmpty(uri.UserInfo) &&
|
||||
|
||||
@@ -31,6 +31,9 @@
|
||||
"Domain": "",
|
||||
"TimeoutSeconds": 15,
|
||||
"MaxRedirects": 5,
|
||||
"AdministrativeProfilePath": "/psulsa/gadmon/capitalhumano/controlincidencias/incidencias.aspx",
|
||||
"MenuProfilePath": "/psulsa/menu.aspx",
|
||||
"MaxProfileBytes": 524288,
|
||||
"AllowedRedirectHosts": [
|
||||
"sgu.ulsa.edu.mx"
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user