Fix and cleanup for Events.WebApi
This commit is contained in:
54
Events-WebApi/Events.Auth/AuthSetupExtensions.cs
Normal file
54
Events-WebApi/Events.Auth/AuthSetupExtensions.cs
Normal 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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user