131 lines
3.6 KiB
C#
131 lines
3.6 KiB
C#
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.Text;
|
|
using Microsoft.OpenApi.Models;
|
|
using System.Reflection;
|
|
using System.Text.Json.Serialization;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
// 1. Configuración de Servicios
|
|
|
|
// a. Configurar servicios de controladores
|
|
builder.Services.AddControllers()
|
|
.ConfigureApiBehaviorOptions(options =>
|
|
{
|
|
options.SuppressModelStateInvalidFilter = true; // Desactiva la validación automática del estado del modelo
|
|
})
|
|
.AddJsonOptions(options =>
|
|
{
|
|
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
|
|
});
|
|
|
|
// b. Configuración de JWT
|
|
var jwtSettings = builder.Configuration.GetSection("Jwt");
|
|
var keyString = jwtSettings["Key"];
|
|
if (string.IsNullOrEmpty(keyString))
|
|
{
|
|
throw new ArgumentNullException("JWT Key is not configured.");
|
|
}
|
|
var key = Encoding.UTF8.GetBytes(keyString);
|
|
|
|
builder.Services.AddAuthentication(options =>
|
|
{
|
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
})
|
|
.AddJwtBearer(options =>
|
|
{
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidIssuer = jwtSettings["Issuer"],
|
|
ValidateAudience = true,
|
|
ValidAudience = jwtSettings["Audience"],
|
|
ValidateLifetime = true,
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"])),
|
|
ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }
|
|
};
|
|
|
|
options.Events = new JwtBearerEvents
|
|
{
|
|
OnAuthenticationFailed = ctx =>
|
|
{
|
|
var logger = ctx.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
|
|
logger.LogError("NOMBRE FALLO {0}", ctx.Exception.GetType().Name);
|
|
logger.LogError("MENSAJE FALLO {0}", ctx.Exception.Message);
|
|
return Task.CompletedTask;
|
|
},
|
|
};
|
|
});
|
|
|
|
// d. Configurar Swagger con soporte para JWT
|
|
builder.Services.AddSwaggerGen(c =>
|
|
{
|
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "SwaggerCamcue API", Version = "v1" });
|
|
|
|
// Definir el esquema de seguridad JWT
|
|
var securityScheme = new OpenApiSecurityScheme
|
|
{
|
|
Name = "Authorization",
|
|
Description = "Ingrese 'Bearer' seguido de su token en el campo de texto.\n\nEjemplo: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...'",
|
|
In = ParameterLocation.Header,
|
|
Type = SecuritySchemeType.Http,
|
|
Scheme = "Bearer",
|
|
BearerFormat = "JWT"
|
|
};
|
|
|
|
c.AddSecurityDefinition("Bearer", securityScheme);
|
|
|
|
|
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
{
|
|
{
|
|
new OpenApiSecurityScheme
|
|
{
|
|
Reference = new OpenApiReference
|
|
{
|
|
Type = ReferenceType.SecurityScheme,
|
|
Id = "Bearer"
|
|
}
|
|
},
|
|
Array.Empty<string>()
|
|
}
|
|
});
|
|
});
|
|
|
|
var app = builder.Build();
|
|
|
|
// 2. Configuración del Pipeline HTTP
|
|
|
|
// b. Habilitar Swagger solo en Desarrollo
|
|
if (app.Environment.IsDevelopment())
|
|
{
|
|
app.UseSwagger();
|
|
app.UseSwaggerUI(c =>
|
|
{
|
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerCamcue API V1");
|
|
c.RoutePrefix = string.Empty; // Swagger en la raíz
|
|
});
|
|
}
|
|
|
|
app.UseCors(policy =>
|
|
{
|
|
policy.AllowAnyOrigin()
|
|
.AllowAnyMethod()
|
|
.AllowAnyHeader();
|
|
});
|
|
|
|
|
|
//app.UseHttpsRedirection();
|
|
// d. Autenticación y Autorización
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
|
|
// e. Mapear Controladores
|
|
app.MapControllers();
|
|
|
|
// f. Ejecutar la Aplicación
|
|
app.Run();
|