First Commit
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
using System.Text;
|
||||
using ADS.Helpers.Auth.Abstractions;
|
||||
using ADS.Helpers.Auth.Implementation;
|
||||
using ADS.Helpers.Auth.Models;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace ADS.Helpers.Auth.Extensions;
|
||||
|
||||
public static class ServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddAdsAuthentication(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services.AddHttpContextAccessor();
|
||||
|
||||
var jwtSection = configuration.GetSection("Jwt");
|
||||
services.Configure<JwtOptions>(jwtSection);
|
||||
|
||||
var jwtOptions = jwtSection.Get<JwtOptions>()
|
||||
?? throw new InvalidOperationException("Jwt configuration missing.");
|
||||
|
||||
var key = new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(jwtOptions.SigningKey));
|
||||
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = jwtOptions.ValidateLifetime,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtOptions.Issuer,
|
||||
ValidAudience = jwtOptions.Audience,
|
||||
IssuerSigningKey = key,
|
||||
ClockSkew = TimeSpan.FromMinutes(jwtOptions.ClockSkewMinutes)
|
||||
};
|
||||
});
|
||||
|
||||
services.AddScoped<IAdsPrincipalAccessor, AdsPrincipalAccessor>();
|
||||
|
||||
// NUEVO: servicio emisor de token (requiere que el host registre validadores)
|
||||
services.AddScoped<IAdsTokenService, AdsTokenService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddAdsAuthorization(
|
||||
this IServiceCollection services)
|
||||
{
|
||||
services.AddAuthorization();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user