Apigateway/ApiGateway/Program.cs

124 lines
2.9 KiB
C#

using ApiGateway;
using Microsoft.Net.Http.Headers;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using MMLib.SwaggerForOcelot.DependencyInjection;
using Ocelot.Provider.Polly;
using ApiGateway.Config;
using ApiGateway.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddOcelotWithSwaggerSupport(options =>
{
options.Folder = "Routes";
});
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
var logger = loggerFactory.CreateLogger("");
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
var pipeConfig = new OcelotPipelineConfiguration
{
AuthorizationMiddleware = async (downStreamContext, next) =>
{
var _bearer_token = downStreamContext.Request.Headers[HeaderNames.Authorization].ToString();
//string date = DateTime.Now.ToString();
//logger.LogInformation("Bearer :");
//logger.LogInformation(_bearer_token);
bool isAuthorized = CustomLogic.Authorize(downStreamContext);
if (isAuthorized)
{
await next.Invoke();
}
else
{
//downStreamContext.Items.SetError(new UnauthenticatedError("Nel wey, no estas autorizado"));
return;
}
}
};
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "MyCors", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
builder.Services.AddOcelot(builder.Configuration).AddPolly();
builder.Services.AddSwaggerForOcelot(builder.Configuration);
//builder.Services.AddCustomJwtAuthentication();
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
builder.Configuration.SetBasePath(Directory.GetCurrentDirectory())
.AddOcelot("Routes", builder.Environment)
.AddEnvironmentVariables();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// Swagger for ocelot
builder.Services.AddSwaggerGen();
builder.Services.AddAuthorization();
builder.Services.AddAuthentication();
var app = builder.Build();
app.UseCors("MyCors");
app.UseSwagger();
if (app.Environment.IsDevelopment())
{
Environment.SetEnvironmentVariable("Mode", "Dev");
}
else
{
Environment.SetEnvironmentVariable("Mode", "Prod");
}
// Cargue de Ocelot
app.UseMiddleware<OcelotResponseMiddleware>();
app.UseSwaggerForOcelotUI(options =>
{
options.PathToSwaggerGenerator = "/swagger/docs";
options.ReConfigureUpstreamSwaggerJson = AlterUpstream.AlterUpstreamSwaggerJson;
}).UseOcelot(pipeConfig).Wait();
app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();
app.MapGet("/", () => "Hello World!");
app.Run();