Fix and cleanup for Events.WebApi

This commit is contained in:
Boris Milašinović
2026-05-11 23:49:25 +02:00
parent 4fb3de19f6
commit b66d05c298
22 changed files with 572 additions and 113 deletions

View File

@@ -0,0 +1,54 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace Events.Auth;
public static class AuthSetupExtensions
{
public static void SetupAuthenticationAndAuthorization(this IServiceCollection services, string authority, string audience)
{
ArgumentException.ThrowIfNullOrWhiteSpace(authority);
ArgumentException.ThrowIfNullOrWhiteSpace(audience);
Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddScoped<IClaimsTransformation, ScopeClaimsTransformation>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.Authority = authority;
opt.Audience = audience;
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidateIssuerSigningKey = true,
NameClaimType = ClaimTypes.NameIdentifier
};
opt.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Append("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
services.AddAuthorization(options =>
{
foreach (var policy in Policies.All)
{
options.AddPolicy(policy.Key, policy.Value);
}
});
}
}