Limpieza, Logging y nuevas rutas

This commit is contained in:
Luis Martinez 2023-01-10 10:35:15 -05:00
parent da19375940
commit 565e971496
11 changed files with 232 additions and 29 deletions

View File

@ -3,7 +3,9 @@ using Ocelot.Configuration;
using Ocelot.Middleware; using Ocelot.Middleware;
using Security; using Security;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Policy;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@ -21,6 +23,9 @@ namespace ApiGateway
//var route2 = ctx.Items.DownstreamRequest(); //Solo el path del request //var route2 = ctx.Items.DownstreamRequest(); //Solo el path del request
//var route3 = ctx.Items.DownstreamRoute(); //Datos full del request //var route3 = ctx.Items.DownstreamRoute(); //Datos full del request
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog());
var logger = loggerFactory.CreateLogger("Auth");
string calledUrl = ctx.Items.DownstreamRoute().UpstreamPathTemplate.OriginalValue; string calledUrl = ctx.Items.DownstreamRoute().UpstreamPathTemplate.OriginalValue;
@ -35,7 +40,7 @@ namespace ApiGateway
try try
{ {
string path = ctx.Request.Path; //string path = ctx.Request.Path;
string authString = ctx.Request.Headers["Authorization"]; string authString = ctx.Request.Headers["Authorization"];
@ -130,6 +135,7 @@ namespace ApiGateway
} }
catch (Exception e) catch (Exception e)
{ {
logger.LogError(71, e.Message);
ctx.Items.SetError(new UnauthenticatedError(e.Message)); ctx.Items.SetError(new UnauthenticatedError(e.Message));
return false; return false;
} }
@ -140,6 +146,12 @@ namespace ApiGateway
{ {
if(_encript.IsValid == false) return false; if(_encript.IsValid == false) return false;
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog());
var logger = loggerFactory.CreateLogger("VerifyToken");
var sb = new StringBuilder()
.AppendLine("Error en: VerifyToken");
var validationParameters = new TokenValidationParameters() var validationParameters = new TokenValidationParameters()
{ {
ValidateIssuer = false, ValidateIssuer = false,
@ -155,16 +167,21 @@ namespace ApiGateway
{ {
tokenHandler.ValidateToken(token, validationParameters, out validatedToken); tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
} }
catch (SecurityTokenException) catch (SecurityTokenException se)
{ {
sb.AppendLine("SecurityTokenException");
sb.AppendLine(se.Message);
logger.LogError(96, sb.ToString());
return false; return false;
} }
catch (Exception e) catch (Exception e)
{ {
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
var logger = loggerFactory.CreateLogger("");
//something else happened //something else happened
logger.LogInformation(e.ToString());
sb.AppendLine("Exception");
sb.AppendLine(e.Message);
logger.LogError(96, sb.ToString());
return false; return false;
//throw; //throw;
@ -191,8 +208,16 @@ namespace ApiGateway
} }
return decryptedText; return decryptedText;
} }
catch (Exception) catch (Exception e)
{ {
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog());
var logger = loggerFactory.CreateLogger("Decrypt");
var sb = new StringBuilder()
.AppendLine("Error en: DesCifrar")
.AppendLine("Exception")
.AppendLine(e.Message);
logger.LogError(96, sb.ToString());
return null; return null;
} }
} }
@ -204,8 +229,16 @@ namespace ApiGateway
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
} }
catch (Exception) catch (Exception e)
{ {
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog());
var logger = loggerFactory.CreateLogger("Base64Decode");
var sb = new StringBuilder()
.AppendLine("Error en: Base64Decode")
.AppendLine("Exception")
.AppendLine(e.Message);
logger.LogError(96, sb.ToString());
return null; return null;
} }
} }

View File

@ -2,6 +2,9 @@
using Ocelot.Logging; using Ocelot.Logging;
using Ocelot.Middleware; using Ocelot.Middleware;
using Ocelot.Responder; using Ocelot.Responder;
using System.IO;
using System.Security.Policy;
using System.Text;
namespace ApiGateway.Middleware namespace ApiGateway.Middleware
{ {
@ -26,14 +29,31 @@ namespace ApiGateway.Middleware
public async Task Invoke(HttpContext httpContext) public async Task Invoke(HttpContext httpContext)
{ {
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog());
var logger = loggerFactory.CreateLogger("ResMiddleware");
string date = DateTime.Now.ToString();
var sb = new StringBuilder()
.Append("Ingreso ResMiddleware: ").AppendLine(date);
await _next.Invoke(httpContext); await _next.Invoke(httpContext);
if (httpContext.Response.HasStarted) if (httpContext.Response.HasStarted)
{
sb.Append("Ingresa al if y return");
logger.LogInformation(69, sb.ToString());
return; return;
}
var errors = httpContext.Items.Errors(); var errors = httpContext.Items.Errors();
if (errors.Count > 0) if (errors.Count > 0)
{ {
Logger.LogWarning($"{errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{httpContext.Request.Path}, request method: {httpContext.Request.Method}"); //Logger.LogWarning($"{errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{httpContext.Request.Path}, request method: {httpContext.Request.Method}");
sb.Append("Hay errores res middleware");
sb.Append("Cant errores: " + errors.Count.ToString());
sb.Append(errors.ToErrorString());
logger.LogError(71, sb.ToString());
var statusCode = _codeMapper.Map(errors); var statusCode = _codeMapper.Map(errors);
var error = string.Join(",", errors.Select(x => x.Message)); var error = string.Join(",", errors.Select(x => x.Message));
@ -43,7 +63,9 @@ namespace ApiGateway.Middleware
} }
else else
{ {
Logger.LogDebug("no pipeline errors, setting and returning completed response"); //Logger.LogDebug("no pipeline errors, setting and returning completed response");
sb.Append("no pipeline errors, setting and returning completed response");
logger.LogInformation(69, sb.ToString());
var downstreamResponse = httpContext.Items.DownstreamResponse(); var downstreamResponse = httpContext.Items.DownstreamResponse();

View File

@ -6,6 +6,9 @@ using MMLib.SwaggerForOcelot.DependencyInjection;
using Ocelot.Provider.Polly; using Ocelot.Provider.Polly;
using ApiGateway.Config; using ApiGateway.Config;
using ApiGateway.Middleware; using ApiGateway.Middleware;
using System.Text;
using System.IO;
using System.Security.Policy;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -16,8 +19,8 @@ builder.Configuration.AddOcelotWithSwaggerSupport(options =>
}); });
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog());
var logger = loggerFactory.CreateLogger(""); var logger = loggerFactory.CreateLogger("Gateway");
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath) builder.Configuration.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true) .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
@ -28,19 +31,37 @@ var pipeConfig = new OcelotPipelineConfiguration
AuthorizationMiddleware = async (downStreamContext, next) => AuthorizationMiddleware = async (downStreamContext, next) =>
{ {
var _bearer_token = downStreamContext.Request.Headers[HeaderNames.Authorization].ToString(); //var _bearer_token = downStreamContext.Request.Headers[HeaderNames.Authorization].ToString();
//string date = DateTime.Now.ToString();
//logger.LogInformation("Bearer :"); //logger.LogInformation("Bearer :");
//logger.LogInformation(_bearer_token); //logger.LogInformation(_bearer_token);
string date = DateTime.Now.ToString();
var url = downStreamContext.Items.DownstreamRoute().UpstreamPathTemplate.OriginalValue;
string path = downStreamContext.Request.Path;
var sb = new StringBuilder()
.Append("Ingreso PipeLine: ").AppendLine(date)
.Append("calledUrl: ").AppendLine(url)
.Append("path: ").AppendLine(path);
logger.LogInformation(69, sb.ToString());
bool isAuthorized = CustomLogic.Authorize(downStreamContext); bool isAuthorized = CustomLogic.Authorize(downStreamContext);
if (isAuthorized) if (isAuthorized)
{ {
var sb2 = new StringBuilder()
.AppendLine("Is authorized: ").Append(isAuthorized)
.AppendLine("Date: ").Append(date);
logger.LogInformation(69, sb2.ToString());
await next.Invoke(); await next.Invoke();
} }
else else
{ {
var sb2 = new StringBuilder()
.Append("Is authorized: ").AppendLine(isAuthorized.ToString())
.Append("Date: ").AppendLine(date)
.Append("Errors: ")
.AppendLine(downStreamContext.Items.Errors().ToString());
logger.LogWarning(27, sb2.ToString());
//downStreamContext.Items.SetError(new UnauthenticatedError("Nel wey, no estas autorizado")); //downStreamContext.Items.SetError(new UnauthenticatedError("Nel wey, no estas autorizado"));
return; return;
} }
@ -53,7 +74,11 @@ builder.Services.AddCors(options =>
{ {
options.AddPolicy(name: "MyCors", builder => options.AddPolicy(name: "MyCors", builder =>
{ {
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); builder
.SetIsOriginAllowed((host) => true)
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
}); });
}); });
@ -104,6 +129,10 @@ else
app.UseMiddleware<OcelotResponseMiddleware>(); app.UseMiddleware<OcelotResponseMiddleware>();
app.UseSwaggerForOcelotUI(options => app.UseSwaggerForOcelotUI(options =>
{ {
var sb = new StringBuilder()
.Append("Inicia ocleot: ");
logger.LogInformation(73, sb.ToString());
options.PathToSwaggerGenerator = "/swagger/docs"; options.PathToSwaggerGenerator = "/swagger/docs";
options.ReConfigureUpstreamSwaggerJson = AlterUpstream.AlterUpstreamSwaggerJson; options.ReConfigureUpstreamSwaggerJson = AlterUpstream.AlterUpstreamSwaggerJson;

View File

@ -7,7 +7,7 @@
{ {
"Name": "MsPing", "Name": "MsPing",
"Version": "1.0", "Version": "1.0",
"Url": "http://localhost:8198/api/swagger/v1/swagger.json" "Url": "http://localhost:8198/swagger/v1/swagger.json"
} }
] ]
}, },

View File

@ -308,7 +308,45 @@
} }
}, },
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Usuarios/NumeroDocumento",
"UpstreamHttpMethod": [ "PATCH" ],
"DownstreamPathTemplate": "/Usuarios/NumeroDocumento",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Auth/RenovarToken",
"UpstreamHttpMethod": [ "PATCH" ],
"DownstreamPathTemplate": "/Auth/RenovarToken",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{ {
"SwaggerKey": "MsAdminUsuarios", "SwaggerKey": "MsAdminUsuarios",

View File

@ -170,6 +170,25 @@
} }
}, },
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/Retirar",
"UpstreamHttpMethod": [ "Post" ],
"DownstreamPathTemplate": "/Afiliados/Retirar",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{ {
"SwaggerKey": "Afiliados", "SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados", "UpstreamPathTemplate": "/Afiliados",
@ -207,6 +226,24 @@
} }
}, },
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/Contacto",
"UpstreamHttpMethod": [ "PATCH" ],
"DownstreamPathTemplate": "/Afiliados/Contacto",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{ {
"SwaggerKey": "Afiliados", "SwaggerKey": "Afiliados",
@ -328,7 +365,7 @@
"UpstreamPathTemplate": "/Archivos/Afiliado", "UpstreamPathTemplate": "/Archivos/Afiliado",
"UpstreamHttpMethod": [ "GET" ], "UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/Archivos/ArchivosUsuario", "DownstreamPathTemplate": "/Archivos/GrupoFamiliar",
"DownstreamScheme": "http", "DownstreamScheme": "http",
"DownstreamHostAndPorts": [ "DownstreamHostAndPorts": [
{ {

View File

@ -1422,10 +1422,15 @@
"GET" "GET"
] ]
}, },
{ {
"SwaggerKey": "MsContratos", "SwaggerKey": "MsContratos",
"UpstreamPathTemplate": "/TarifasPorMDT", "UpstreamPathTemplate": "/TarifasPorCUPMDT/CargueMasivo",
"DownstreamPathTemplate": "/TarifasPorMDT", "DownstreamPathTemplate": "/TarifasPorCUPMDT/CargueMasivo",
"DownstreamScheme": "http", "DownstreamScheme": "http",
"DownstreamHostAndPorts": [ "DownstreamHostAndPorts": [
{ {
@ -1437,8 +1442,27 @@
"permisos": "any" "permisos": "any"
}, },
"UpstreamHttpMethod": [ "UpstreamHttpMethod": [
"PATCH" "POST"
]
},
{
"SwaggerKey": "MsContratos",
"UpstreamPathTemplate": "/Cups/CargueMasivo",
"DownstreamPathTemplate": "/Cups/CargueMasivo",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8149
}
],
"RouteClaimsRequirement": {
"permisos": "any"
},
"UpstreamHttpMethod": [
"POST"
] ]
} }
] ]
} }

View File

@ -5,7 +5,7 @@
"SwaggerKey": "MsPing", "SwaggerKey": "MsPing",
"UpstreamPathTemplate": "/Ping", "UpstreamPathTemplate": "/Ping",
"UpstreamHttpMethod": [ "GET", "POST", "PATCH" ], "UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/Ping", "DownstreamPathTemplate": "/Ping",
"DownstreamScheme": "http", "DownstreamScheme": "http",
@ -16,6 +16,25 @@
} }
], ],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsPing",
"UpstreamPathTemplate": "/log",
"UpstreamHttpMethod": [ "GET"],
"DownstreamPathTemplate": "/Log",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8198
}
],
"RouteClaimsRequirement": { "RouteClaimsRequirement": {
"permisos": "any" "permisos": "any"
} }

View File

@ -1,10 +1,9 @@
{ {
"Logging": { "Logging": {
"EventLog": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information"
"System": "Information", }
"Microsoft": "Information",
"Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*"

File diff suppressed because one or more lines are too long

View File

@ -11,7 +11,9 @@ builder.Services.AddSwaggerGen();
builder.Services.AddCors(options => { builder.Services.AddCors(options => {
options.AddPolicy(name: "widthoutCors", options.AddPolicy(name: "widthoutCors",
builder => { builder => {
builder.AllowAnyOrigin() builder
.SetIsOriginAllowed((host) => true)
.AllowAnyOrigin()
.AllowAnyMethod() .AllowAnyMethod()
.AllowAnyHeader(); .AllowAnyHeader();
}); });
@ -33,7 +35,7 @@ else
Environment.SetEnvironmentVariable("Mode", "Prod"); Environment.SetEnvironmentVariable("Mode", "Prod");
} }
app.UseHttpsRedirection(); //app.UseHttpsRedirection();
app.UseAuthorization(); app.UseAuthorization();