Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add issuer/scheme mapping middleware to improve authentication perf #287

Merged
merged 4 commits into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,16 @@ public static IServiceCollection AddDialogportenAuthentication(
{
OnMessageReceived = async context =>
{
var issuerCache = context.HttpContext.RequestServices.GetRequiredService<ITokenIssuerCache>();
var expectedIssuer = await issuerCache.GetIssuerForScheme(schema.Name);
if (context.HttpContext.Items.TryGetValue(Constants.CurrentTokenIssuer, out var issuerObject))
var expectedIssuer = await context.HttpContext
.RequestServices
.GetRequiredService<ITokenIssuerCache>()
.GetIssuerForScheme(schema.Name);

if (context.HttpContext.Items.TryGetValue(Constants.CurrentTokenIssuer, out var tokenIssuer)
&& (string?)tokenIssuer != expectedIssuer)
{
var actualIssuer = issuerObject as string;
if (actualIssuer != expectedIssuer)
{
context.NoResult();
return;
}
context.NoResult();
return;
elsand marked this conversation as resolved.
Show resolved Hide resolved
}
}
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Protocols;
using System.Collections.ObjectModel;
using Microsoft.Extensions.Options;

namespace Digdir.Domain.Dialogporten.WebApi.Common.Authentication;

Expand All @@ -9,20 +10,20 @@ public interface ITokenIssuerCache
public Task<string?> GetIssuerForScheme(string schemeName);
}

public class TokenIssuerCache : ITokenIssuerCache, IDisposable
public sealed class TokenIssuerCache : ITokenIssuerCache, IDisposable
{
private readonly Dictionary<string, string> _issuerMappings = new();
private readonly SemaphoreSlim _initializationSemaphore = new(1, 1);
private bool _initialized;
private readonly IEnumerable<JwtBearerTokenSchemasOptions>? _jwtTokenSchemas;
private readonly IReadOnlyCollection<JwtBearerTokenSchemasOptions> _jwtTokenSchemas;

public TokenIssuerCache(IConfiguration configuration)
public TokenIssuerCache(IOptions<WebApiSettings> apiSettings)
{
_jwtTokenSchemas = configuration
.GetSection(WebApiSettings.SectionName)
.Get<WebApiSettings>()
?.Authentication
?.JwtBearerTokenSchemas;
_jwtTokenSchemas = apiSettings
.Value
.Authentication
.JwtBearerTokenSchemas
?? throw new ArgumentException("JwtBearerTokenSchemas is required.");
}

public async Task<string?> GetIssuerForScheme(string schemeName)
Expand All @@ -35,42 +36,30 @@ public TokenIssuerCache(IConfiguration configuration)

private async Task EnsureInitializedAsync()
{
if (!_initialized && _jwtTokenSchemas != null)
{
await _initializationSemaphore.WaitAsync();
try
{
if (!_initialized)
{
foreach (var schema in _jwtTokenSchemas)
{
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
schema.WellKnown, new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();
_issuerMappings[schema.Name] = config.Issuer;
}
if (_initialized) return;
await _initializationSemaphore.WaitAsync();
if (_initialized) return;

_initialized = true;
}
}
finally
try
{
foreach (var schema in _jwtTokenSchemas)
{
_initializationSemaphore.Release();
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
schema.WellKnown, new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();
_issuerMappings[schema.Name] = config.Issuer;
}

_initialized = true;
}
finally
{
_initializationSemaphore.Release();
}
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_initializationSemaphore.Dispose();
}
_initializationSemaphore.Dispose();
}
}
3 changes: 2 additions & 1 deletion src/Digdir.Domain.Dialogporten.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ static void BuildAndRun(string[] args)
app.UseHttpsRedirection()
.UseSerilogRequestLogging()
.UseProblemDetailsExceptionHandler()
.UseDialogportenAuthentication()
.UseMiddleware<JwtSchemeSelectorMiddleware>()
elsand marked this conversation as resolved.
Show resolved Hide resolved
.UseAuthentication()
.UseAuthorization()
.UseAzureConfiguration()
.UseFastEndpoints(x =>
Expand Down