audit, advisories and doctors/setup work
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace StellaOps.SbomService.Auth;
|
||||
|
||||
internal sealed class HeaderAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
public const string SchemeName = "SbomHeader";
|
||||
|
||||
#pragma warning disable CS0618 // ISystemClock obsolete; base ctor signature still requires it on this TF.
|
||||
public HeaderAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
ISystemClock clock) : base(options, logger, encoder, clock)
|
||||
{
|
||||
}
|
||||
#pragma warning restore CS0618
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (!TryGetHeader("x-tenant-id", out var tenantId) &&
|
||||
!TryGetHeader("tid", out tenantId))
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.Fail("tenant_header_missing"));
|
||||
}
|
||||
|
||||
var userId = TryGetHeader("x-user-id", out var headerUser)
|
||||
? headerUser
|
||||
: "system";
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, userId),
|
||||
new Claim("tenant", tenantId),
|
||||
new Claim("tenant_id", tenantId)
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(userId))
|
||||
{
|
||||
claims.Add(new Claim("user", userId));
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(claims, SchemeName);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, SchemeName);
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
|
||||
private bool TryGetHeader(string name, out string value)
|
||||
{
|
||||
value = string.Empty;
|
||||
if (!Request.Headers.TryGetValue(name, out var headerValues))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var headerValue = headerValues.ToString().Trim();
|
||||
if (string.IsNullOrWhiteSpace(headerValue))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
value = headerValue;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user