From c750ae7f0f80bec9d55f504f12c90ed3c09354dd Mon Sep 17 00:00:00 2001 From: luismd98 Date: Wed, 2 Nov 2022 12:06:54 -0500 Subject: [PATCH] =?UTF-8?q?Limpieza=20de=20c=C3=B3digo=20y=20dependencias?= =?UTF-8?q?=20obsoletas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ApiGateway/ApiGateway.csproj | 1 - ApiGateway/CustomLogic.cs | 53 +++------ ApiGateway/Loggin.cs | 73 ------------ .../{ => Middleware}/OcelotJwtMiddleware.cs | 58 +++------- .../OcelotResponseMiddleware.cs | 14 +-- ApiGateway/Program.cs | 31 +----- ApiGateway/Trash/ocelot - Copy.json | 105 ------------------ ApiGateway/Trash/ocelot2.json | 19 ---- AuthWebApi/AuthWebApi.csproj | 13 --- AuthWebApi/Controllers/AccountController.cs | 31 ------ AuthWebApi/Program.cs | 18 --- AuthWebApi/Properties/launchSettings.json | 30 ----- AuthWebApi/appsettings.Development.json | 8 -- AuthWebApi/appsettings.json | 9 -- BackApiGateway.sln | 12 +- JwtAuthManager/CustomJwtAuthExtension.cs | 40 ------- JwtAuthManager/JwtAuthManager.csproj | 16 --- JwtAuthManager/JwtTokenHandler.cs | 81 -------------- JwtAuthManager/Models/AuthRequest.cs | 14 --- JwtAuthManager/Models/AuthResponse.cs | 15 --- JwtAuthManager/Models/UserAccount.cs | 17 --- TestApi1/.config/dotnet-tools.json | 12 -- .../Controllers/WeatherForecastController.cs | 45 -------- TestApi1/Program.cs | 25 ----- TestApi1/Properties/launchSettings.json | 31 ------ TestApi1/TestApi1.csproj | 13 --- TestApi1/WeatherForecast.cs | 13 --- TestApi1/appsettings.Development.json | 8 -- TestApi1/appsettings.json | 9 -- TestApi2/.config/dotnet-tools.json | 12 -- TestApi2/Controllers/ContratosController.cs | 28 ----- .../Controllers/WeatherForecastController.cs | 45 -------- TestApi2/Program.cs | 28 ----- TestApi2/Properties/launchSettings.json | 31 ------ TestApi2/TestApi2.csproj | 17 --- TestApi2/WeatherForecast.cs | 13 --- TestApi2/appsettings.Development.json | 8 -- TestApi2/appsettings.json | 9 -- 38 files changed, 44 insertions(+), 961 deletions(-) delete mode 100644 ApiGateway/Loggin.cs rename ApiGateway/{ => Middleware}/OcelotJwtMiddleware.cs (52%) rename ApiGateway/{ => Middleware}/OcelotResponseMiddleware.cs (82%) delete mode 100644 ApiGateway/Trash/ocelot - Copy.json delete mode 100644 ApiGateway/Trash/ocelot2.json delete mode 100644 AuthWebApi/AuthWebApi.csproj delete mode 100644 AuthWebApi/Controllers/AccountController.cs delete mode 100644 AuthWebApi/Program.cs delete mode 100644 AuthWebApi/Properties/launchSettings.json delete mode 100644 AuthWebApi/appsettings.Development.json delete mode 100644 AuthWebApi/appsettings.json delete mode 100644 JwtAuthManager/CustomJwtAuthExtension.cs delete mode 100644 JwtAuthManager/JwtAuthManager.csproj delete mode 100644 JwtAuthManager/JwtTokenHandler.cs delete mode 100644 JwtAuthManager/Models/AuthRequest.cs delete mode 100644 JwtAuthManager/Models/AuthResponse.cs delete mode 100644 JwtAuthManager/Models/UserAccount.cs delete mode 100644 TestApi1/.config/dotnet-tools.json delete mode 100644 TestApi1/Controllers/WeatherForecastController.cs delete mode 100644 TestApi1/Program.cs delete mode 100644 TestApi1/Properties/launchSettings.json delete mode 100644 TestApi1/TestApi1.csproj delete mode 100644 TestApi1/WeatherForecast.cs delete mode 100644 TestApi1/appsettings.Development.json delete mode 100644 TestApi1/appsettings.json delete mode 100644 TestApi2/.config/dotnet-tools.json delete mode 100644 TestApi2/Controllers/ContratosController.cs delete mode 100644 TestApi2/Controllers/WeatherForecastController.cs delete mode 100644 TestApi2/Program.cs delete mode 100644 TestApi2/Properties/launchSettings.json delete mode 100644 TestApi2/TestApi2.csproj delete mode 100644 TestApi2/WeatherForecast.cs delete mode 100644 TestApi2/appsettings.Development.json delete mode 100644 TestApi2/appsettings.json diff --git a/ApiGateway/ApiGateway.csproj b/ApiGateway/ApiGateway.csproj index bd93d7f..704082a 100644 --- a/ApiGateway/ApiGateway.csproj +++ b/ApiGateway/ApiGateway.csproj @@ -29,7 +29,6 @@ - diff --git a/ApiGateway/CustomLogic.cs b/ApiGateway/CustomLogic.cs index 496546b..6dca65d 100644 --- a/ApiGateway/CustomLogic.cs +++ b/ApiGateway/CustomLogic.cs @@ -1,5 +1,4 @@ -using JwtAuthManager; -using Microsoft.IdentityModel.Tokens; +using Microsoft.IdentityModel.Tokens; using Ocelot.Configuration; using Ocelot.Middleware; using Security; @@ -18,20 +17,18 @@ namespace ApiGateway public static bool Authorize(HttpContext ctx) { // Solo para test - string seguimiento = ctx.Request.Headers["Potato"]; - var route2 = ctx.Items.DownstreamRequest(); //Solo el path del request - var route3 = ctx.Items.DownstreamRoute(); //Datos full del request - var calledUrl = ctx.Items.DownstreamRoute().UpstreamPathTemplate.OriginalValue; + //string seguimiento = ctx.Request.Headers["Potato"]; + //var route2 = ctx.Items.DownstreamRequest(); //Solo el path del request + //var route3 = ctx.Items.DownstreamRoute(); //Datos full del request - var isLogin = calledUrl == "/Ext/Login" ; - var isExtLogin = calledUrl == "/Auth/Login"; + + string calledUrl = ctx.Items.DownstreamRoute().UpstreamPathTemplate.OriginalValue; // Excepcion para login, no requiere token if (String.Equals(calledUrl, "/Ext/Login") || String.Equals(calledUrl, "/Auth/Login")) return true; - //if (isLogin == true || isExtLogin == true) return true; try { @@ -43,12 +40,12 @@ namespace ApiGateway string? signature = ctx.Request.Headers["Signature"]; signature = Base64Decode(signature); - - if (authString.IsNullOrEmpty()) throw new Exception("Nel wey, no hay token"); + + if (String.IsNullOrEmpty(authString)) throw new Exception("Nel wey, no hay token"); string? jwtDescifrado = DesCifrar(authString.Replace("Bearer ", "")); - if (jwtDescifrado.IsNullOrEmpty()) throw new Exception("Nel wey, token inválido"); + if (String.IsNullOrEmpty(jwtDescifrado)) throw new Exception("Nel wey, token inválido"); var jwtToken = new JwtSecurityToken(jwtDescifrado); @@ -57,12 +54,10 @@ namespace ApiGateway //Claims dentro del .json DownstreamRoute? route = (DownstreamRoute?)ctx.Items["DownstreamRoute"]; + + // Si no hay claims (requerimiento de Permisos) permite pasar sin problemas if (route == null || route.RouteClaimsRequirement.Count == 0) return true; - //flag for authorization // Para iterar multples roles, no usados ya que se usa solo con 1 - //bool auth = false; - - //where are stored the claims of the jwt token //Claims del token Claim[] claims = jwtToken.Claims.ToArray(); @@ -112,27 +107,20 @@ namespace ApiGateway return true; } - //Si no hay perfil seleccionado - if (signature.IsNullOrEmpty()) + //Si no hay perfil seleccionado + if (String.IsNullOrEmpty(signature)) throw new Exception("Falta el perfil, no mames"); bool aplicaRolSeleccionado = rolesLst.Any(signature!.Contains); //Aqui remuevo los :: teniendo en cuenta key == permisos cl.Value - //if (cl.Value == m.Value) if (String.Equals(newPermiso, m.Value) && aplicaRolSeleccionado == true) { return true; - //cont++; //NO NECESARIO porque solo hay 1 permiso por request } } } } - //if (cont == matchesand.Count) - //{ - // return true; - // // break; - //} } } return false; @@ -142,11 +130,6 @@ namespace ApiGateway ctx.Items.SetError(new UnauthenticatedError(e.Message)); return false; } - - /// - //return true; - /// - } @@ -159,12 +142,11 @@ namespace ApiGateway ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true, - //IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtTokenHandler.JWT_SECURITY_KEY)) - IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Encripter.HashKey)) + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Encripter.HashKey!)) }; var tokenHandler = new JwtSecurityTokenHandler(); - SecurityToken validatedToken = null; + SecurityToken? validatedToken = null; try { @@ -184,7 +166,7 @@ namespace ApiGateway return false; //throw; } - //... manual validations return false if anything untoward is discovered + //... Si el token es invalido (=null) devuelve false return validatedToken != null; } @@ -194,7 +176,8 @@ namespace ApiGateway try { string? b64Decrypted = Base64Decode(value); - if (b64Decrypted.IsNullOrEmpty()) return null; + + if (String.IsNullOrEmpty(b64Decrypted)) return null; string decryptedText = ""; for (int i = 0; i < b64Decrypted!.Length; i++) diff --git a/ApiGateway/Loggin.cs b/ApiGateway/Loggin.cs deleted file mode 100644 index a213791..0000000 --- a/ApiGateway/Loggin.cs +++ /dev/null @@ -1,73 +0,0 @@ -using Kros.Extensions; -using Microsoft.Extensions.Primitives; - -namespace ApiGateway -{ - public class Loggin - { - //public string GetRequestIP(HttpContext ctx, bool tryUseXForwardHeader = true) - //{ - // string ip = null; - - // // todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For - - // // X-Forwarded-For (csv list): Using the First entry in the list seems to work - // // for 99% of cases however it has been suggested that a better (although tedious) - // // approach might be to read each IP from right to left and use the first public IP. - // // http://stackoverflow.com/a/43554000/538763 - // // - // if (tryUseXForwardHeader) - // { - // ip = GetHeaderValueAs(ctx, "X-Forwarded-For"); - // ip = SplitCsv(ip).FirstOrDefault(); - - // } - - // // RemoteIpAddress is always null in DNX RC1 Update1 (bug). - // if (IsNullOrWhitespace(ip) && ctx?.Connection?.RemoteIpAddress != null) - // ip = ctx.Connection.RemoteIpAddress.ToString(); - - // if (IsNullOrWhitespace(ip)) - // ip = GetHeaderValueAs(ctx, "REMOTE_ADDR"); - - // // _httpContextAccessor.HttpContext?.Request?.Host this is the local host. - - // if (IsNullOrWhitespace(ip)) - // throw new Exception("Unable to determine caller's IP."); - - // return ip; - //} - - //public T GetHeaderValueAs(HttpContext ctx, string headerName) - //{ - // StringValues values; - - // if (ctx?.Request?.Headers?.TryGetValue(headerName, out values) ?? false) - // { - // string rawValues = values.ToString(); // writes out as Csv when there are multiple. - - // if (!IsNullOrWhitespace(rawValues)) - // return (T)Convert.ChangeType(values.ToString(), typeof(T)); - // } - // return default(T); - //} - - //public List SplitCsv(string csvList, bool nullOrWhitespaceInputReturnsNull = false) - //{ - // if (string.IsNullOrWhiteSpace(csvList)) - // return nullOrWhitespaceInputReturnsNull ? null : new List(); - - // return csvList - // .TrimEnd(',') - // .Split(',') - // .AsEnumerable() - // .Select(s => s.Trim()) - // .ToList(); - //} - - //public bool IsNullOrWhitespace(string s) - //{ - // return String.IsNullOrWhiteSpace(s); - //} - } -} diff --git a/ApiGateway/OcelotJwtMiddleware.cs b/ApiGateway/Middleware/OcelotJwtMiddleware.cs similarity index 52% rename from ApiGateway/OcelotJwtMiddleware.cs rename to ApiGateway/Middleware/OcelotJwtMiddleware.cs index 9a13dd7..3607d55 100644 --- a/ApiGateway/OcelotJwtMiddleware.cs +++ b/ApiGateway/Middleware/OcelotJwtMiddleware.cs @@ -1,25 +1,23 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.Net.Http.Headers; +using Microsoft.Net.Http.Headers; using Ocelot.Middleware; -using Ocelot.RequestId; -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.Net.Http.Headers; -namespace ApiGateway +namespace ApiGateway.Middleware { public class OcelotJwtMiddleware : OcelotPipelineConfiguration { private static readonly string RoleSeparator = ","; - + /* + + + Nota: No tengo ni idea de por qué este método es necesario, pero hace que funcione... + + + */ public OcelotJwtMiddleware() { PreAuthorizationMiddleware = async (ctx, next) => @@ -28,7 +26,7 @@ namespace ApiGateway }; } - public async Task ProcessRequest(HttpContext context, System.Func next) + public async Task ProcessRequest(HttpContext context, Func next) { //var _bearer_token = context.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", ""); @@ -41,10 +39,10 @@ namespace ApiGateway var logger = loggerFactory.CreateLogger(""); - logger.LogInformation("Potato 3"); - logger.LogInformation("Bearer:"); - logger.LogInformation(_bearer_token); - logger.LogDebug("Potato 4"); + //logger.LogInformation("Potato 3"); + //logger.LogInformation("Bearer:"); + //logger.LogInformation(_bearer_token); + //logger.LogDebug("Potato 4"); // Get the the any service object, if required //var anyService = context.RequestServices.GetService(typeof()); @@ -78,33 +76,5 @@ namespace ApiGateway await context.Response.WriteAsync(msg); } - //public static Func< DownstreamContext, Func, Task> CreateAuthorizationFilter - // => async (downStreamContext, next) => - // { - // HttpContext httpContext = downStreamContext.HttpContext; - // var token = httpContext.Request.Cookies[JwtManager.AuthorizationTokenKey]; - // if (token != null && AuthorizeIfValidToken(downStreamContext, token)) - // { - // await next.Invoke(); - // } - // else - // { - // downStreamContext.DownstreamResponse = - // new DownstreamResponse(new HttpResponseMessage(HttpStatusCode.Unauthorized)); - // } - // }; - - //private static bool AuthorizeIfValidToken(DownstreamContext downStreamContext, string jwtToken) - //{ - // IIdentityProvider decodedObject = new JwtManager().Decode(jwtToken); - // if (decodedObject != null) - // { - // return downStreamContext.DownstreamReRoute.RouteClaimsRequirement["Role"] - // ?.Split(RoleSeparator) - // .FirstOrDefault(role => role.Trim() == decodedObject.GetRole()) != default; - // } - - // return false; - //} } } diff --git a/ApiGateway/OcelotResponseMiddleware.cs b/ApiGateway/Middleware/OcelotResponseMiddleware.cs similarity index 82% rename from ApiGateway/OcelotResponseMiddleware.cs rename to ApiGateway/Middleware/OcelotResponseMiddleware.cs index 0f9f8c9..ec93b2c 100644 --- a/ApiGateway/OcelotResponseMiddleware.cs +++ b/ApiGateway/Middleware/OcelotResponseMiddleware.cs @@ -3,18 +3,9 @@ using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Responder; - -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.Caching.Memory; -using Ocelot.Authorization; -using System.Text.RegularExpressions; - -namespace ApiGateway +namespace ApiGateway.Middleware { - public class OcelotResponseMiddleware : Ocelot.Middleware.OcelotMiddleware + public class OcelotResponseMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; private readonly IHttpResponder _responder; @@ -34,7 +25,6 @@ namespace ApiGateway public async Task Invoke(HttpContext httpContext) { - //var x = CustomLogic.Authorize(httpContext); await _next.Invoke(httpContext); if (httpContext.Response.HasStarted) diff --git a/ApiGateway/Program.cs b/ApiGateway/Program.cs index ddf8b33..f62cbba 100644 --- a/ApiGateway/Program.cs +++ b/ApiGateway/Program.cs @@ -1,14 +1,11 @@ using ApiGateway; -using JwtAuthManager; using Microsoft.Net.Http.Headers; -using Ocelot.Authorization; using Ocelot.DependencyInjection; using Ocelot.Middleware; using MMLib.SwaggerForOcelot.DependencyInjection; using Ocelot.Provider.Polly; using ApiGateway.Config; -using System.Net; -using Microsoft.AspNetCore.Http; +using ApiGateway.Middleware; var builder = WebApplication.CreateBuilder(args); @@ -31,23 +28,11 @@ var pipeConfig = new OcelotPipelineConfiguration AuthorizationMiddleware = async (downStreamContext, next) => { - //Authorize(downStreamContext); - var _bearer_token = downStreamContext.Request.Headers[HeaderNames.Authorization].ToString(); - - logger.LogInformation("Bearer 2:"); + logger.LogInformation("Bearer :"); logger.LogInformation(_bearer_token); - //await next.Invoke(); - //downStreamContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; - //await downStreamContext.Response.WriteAsync("Nel wey "); - //downStreamContext.Items.SetError(new UnauthenticatedError("Ni modo, wey")); - //return; - - //var cifrado = Encipher(_bearer_token, cipherKey); - - //var descifrado = Decipher(cifrado, cipherKey); bool isAuthorized = CustomLogic.Authorize(downStreamContext); if (isAuthorized) { @@ -74,7 +59,7 @@ builder.Services.AddCors(options => builder.Services.AddOcelot(builder.Configuration).AddPolly(); builder.Services.AddSwaggerForOcelot(builder.Configuration); -builder.Services.AddCustomJwtAuthentication(); +//builder.Services.AddCustomJwtAuthentication(); var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); @@ -100,15 +85,10 @@ builder.Services.AddAuthentication(); var app = builder.Build(); - app.UseCors("MyCors"); -//app.UseCors("widthoutCors"); app.UseSwagger(); -//Configure the HTTP request pipeline. -//if (app.Environment.IsDevelopment() || app.Environment.IsProduction()) -//{ -//} + if (app.Environment.IsDevelopment()) { Environment.SetEnvironmentVariable("Mode", "Dev"); @@ -119,9 +99,6 @@ else } -//IApplicationBuilder config2 = new IApplicationBuilder - - // Cargue de Ocelot app.UseMiddleware(); app.UseSwaggerForOcelotUI(options => diff --git a/ApiGateway/Trash/ocelot - Copy.json b/ApiGateway/Trash/ocelot - Copy.json deleted file mode 100644 index 07bf6c3..0000000 --- a/ApiGateway/Trash/ocelot - Copy.json +++ /dev/null @@ -1,105 +0,0 @@ -{ - "Routes": [ - - { - //Incoming - "UpstreamPathTemplate": "/api/Account", - "UpstreamHttpMethod": [ "POST" ], - - //Routed - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 5151 - } - ], - "DownstreamPathTemplate": "/api/Account" - }, - - - { - //Incoming - "UpstreamPathTemplate": "/Contratos", - "UpstreamHttpMethod": [ "GET", "POST" ], - - //Routed - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 5102 - } - ], - "DownstreamPathTemplate": "/api/Contratos", - "AuthenticationOptions": { - //"AuthenticationProviderKey": "Bearer", - "AllowedScopes": ["0kmmpshnyd.execute-api.us-east-2.amazonaws.com/"] // Ejemplo: "api.portfolio.manager.v1" - } - }, - - - - { - //Incoming - "UpstreamPathTemplate": "/Test", - "UpstreamHttpMethod": [ "GET", "POST" ], - - //Routed - "DownstreamScheme": "https", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 7041 - } - ], - "DownstreamPathTemplate": "/ApiTest", - - //Auth - "AuthenticationOptions": { - //"AuthenticationProviderKey": "Bearer", - "AllowedScopes": [] // Ejemplo: "api.portfolio.manager.v1" - }, - "RouteClaimsRequirement": { - "permiso": "nuepDLYs7n8=" - } - }, - - - - { - "UpstreamPathTemplate": "/Test/{id}", - "UpstreamHttpMethod": [ "DELETE" ], - - "DownstreamScheme": "https", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 7041 - } - ], - "DownstreamPathTemplate": "/ApiTest/{id}", - - // - "RateLimitOptions": { - "ClientWhiteList": [], - "EnableRateLimiting": true, - "Period": "5s", //s =sec, m = min, h = hour, d = day // Solo puede hacer request en x tiempo - "PeriodTimespan": 10, // reintentar luego de x tiempo si entra en el error del period - "Limit": 1 //Request que puede hacer 1 cliente - } - - } - ], - - - - "GlobalConfiguration": { - "BaseUrl": "https://localhost:7041", - "RateLimitOptions": { - "QuotaExceededMessage": "Request excedidos", - "HttpStatusCode": 909 //429 default - } - } - -} \ No newline at end of file diff --git a/ApiGateway/Trash/ocelot2.json b/ApiGateway/Trash/ocelot2.json deleted file mode 100644 index 54ce45e..0000000 --- a/ApiGateway/Trash/ocelot2.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "Routes": [ - { - "UpstreamPathTemplate": "/ApiTest", - "UpstreamHttpMethod": [ "GET", "POST" ], - - "DownstreamScheme": "https", - "DownstreamHostAndPorts": [ - "Host": "localhost", - "Port" : 7041 - ] - } - ], - - "GlobalConfiguration": { - "BaseUrl": "https://localhost:7041" - } - -} \ No newline at end of file diff --git a/AuthWebApi/AuthWebApi.csproj b/AuthWebApi/AuthWebApi.csproj deleted file mode 100644 index 40b6173..0000000 --- a/AuthWebApi/AuthWebApi.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - diff --git a/AuthWebApi/Controllers/AccountController.cs b/AuthWebApi/Controllers/AccountController.cs deleted file mode 100644 index 105ca80..0000000 --- a/AuthWebApi/Controllers/AccountController.cs +++ /dev/null @@ -1,31 +0,0 @@ -using JwtAuthManager; -using JwtAuthManager.Models; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; - -namespace AuthWebApi.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class AccountController : ControllerBase - { - private readonly JwtTokenHandler _jwtTokenHandler; - - public AccountController(JwtTokenHandler jwtTokenHandler) - { - _jwtTokenHandler = jwtTokenHandler; - } - - [HttpPost] - public ActionResult Authenticate([FromBody] AuthRequest authRequest) - { - var authResponse = _jwtTokenHandler.GenerateJwtToken(authRequest); - if(authResponse == null) return Unauthorized(); - return Ok(authResponse); - } - - -// https://localhost:7041/ApiTest post get -//https://localhost:7041/ApiTest/{id} delete - } -} diff --git a/AuthWebApi/Program.cs b/AuthWebApi/Program.cs deleted file mode 100644 index 191eac7..0000000 --- a/AuthWebApi/Program.cs +++ /dev/null @@ -1,18 +0,0 @@ -using JwtAuthManager; - -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. - -builder.Services.AddControllers(); -builder.Services.AddSingleton(); - -var app = builder.Build(); - -// Configure the HTTP request pipeline. - -app.UseAuthorization(); - -app.MapControllers(); - -app.Run(); diff --git a/AuthWebApi/Properties/launchSettings.json b/AuthWebApi/Properties/launchSettings.json deleted file mode 100644 index 874525c..0000000 --- a/AuthWebApi/Properties/launchSettings.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "profiles": { - "AuthWebApi": { - "commandName": "Project", - "launchUrl": "weatherforecast", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "dotnetRunMessages": true, - "applicationUrl": "http://localhost:5151" - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "weatherforecast", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - }, - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:33553", - "sslPort": 0 - } - } -} \ No newline at end of file diff --git a/AuthWebApi/appsettings.Development.json b/AuthWebApi/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/AuthWebApi/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/AuthWebApi/appsettings.json b/AuthWebApi/appsettings.json deleted file mode 100644 index 10f68b8..0000000 --- a/AuthWebApi/appsettings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/BackApiGateway.sln b/BackApiGateway.sln index 9739c13..698a8f4 100644 --- a/BackApiGateway.sln +++ b/BackApiGateway.sln @@ -7,12 +7,14 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApiGateway", "ApiGateway", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "ApiGateway\ApiGateway.csproj", "{AC631810-7FAF-4C9A-A35D-3EC538A49810}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JwtAuthManager", "JwtAuthManager\JwtAuthManager.csproj", "{787DFE08-2E54-4833-AF3E-5979B676B042}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Auth", "Auth\Auth.csproj", "{76522272-9D28-4168-8296-AFC933D22650}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegradorBE", "IntegradorBE\IntegradorBE.csproj", "{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{F491CF9B-9CF8-4F3B-BBD7-A282F7DC1D6D}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Microservices", "Microservices", "{A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -23,10 +25,6 @@ Global {AC631810-7FAF-4C9A-A35D-3EC538A49810}.Debug|Any CPU.Build.0 = Debug|Any CPU {AC631810-7FAF-4C9A-A35D-3EC538A49810}.Release|Any CPU.ActiveCfg = Release|Any CPU {AC631810-7FAF-4C9A-A35D-3EC538A49810}.Release|Any CPU.Build.0 = Release|Any CPU - {787DFE08-2E54-4833-AF3E-5979B676B042}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {787DFE08-2E54-4833-AF3E-5979B676B042}.Debug|Any CPU.Build.0 = Debug|Any CPU - {787DFE08-2E54-4833-AF3E-5979B676B042}.Release|Any CPU.ActiveCfg = Release|Any CPU - {787DFE08-2E54-4833-AF3E-5979B676B042}.Release|Any CPU.Build.0 = Release|Any CPU {76522272-9D28-4168-8296-AFC933D22650}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {76522272-9D28-4168-8296-AFC933D22650}.Debug|Any CPU.Build.0 = Debug|Any CPU {76522272-9D28-4168-8296-AFC933D22650}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -41,6 +39,8 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {AC631810-7FAF-4C9A-A35D-3EC538A49810} = {9F5D8D1C-CF99-4BDD-8497-0123656B8A48} + {76522272-9D28-4168-8296-AFC933D22650} = {F491CF9B-9CF8-4F3B-BBD7-A282F7DC1D6D} + {9562FA86-4AEF-43E2-A6F6-D60AF09BCA12} = {A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {EC576D5A-ADE3-40CC-BF55-7E52E6F18AC4} diff --git a/JwtAuthManager/CustomJwtAuthExtension.cs b/JwtAuthManager/CustomJwtAuthExtension.cs deleted file mode 100644 index 08cb353..0000000 --- a/JwtAuthManager/CustomJwtAuthExtension.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.IdentityModel.Tokens; -using System.Text; - -namespace JwtAuthManager -{ - public static class CustomJwtAuthExtension - { - - //private readonly ILogger _logger; - - //public CustomJwtAuthExtension(ILogger<> logger) - //{ - // _logger = (ILogger?)logger; - //} - - public static void AddCustomJwtAuthentication(this IServiceCollection services) - { - - services.AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }).AddJwtBearer(options => - { - options.IncludeErrorDetails = true; - options.RequireHttpsMetadata = true; - options.SaveToken = true; - options.TokenValidationParameters = new TokenValidationParameters - { - ValidateIssuer = false, - ValidateAudience = false, - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtTokenHandler.JWT_SECURITY_KEY)) - }; - }); - } - } -} diff --git a/JwtAuthManager/JwtAuthManager.csproj b/JwtAuthManager/JwtAuthManager.csproj deleted file mode 100644 index 02c9b0f..0000000 --- a/JwtAuthManager/JwtAuthManager.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - diff --git a/JwtAuthManager/JwtTokenHandler.cs b/JwtAuthManager/JwtTokenHandler.cs deleted file mode 100644 index 8484262..0000000 --- a/JwtAuthManager/JwtTokenHandler.cs +++ /dev/null @@ -1,81 +0,0 @@ -using JwtAuthManager.Models; -using Microsoft.IdentityModel.Tokens; -using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; - -namespace JwtAuthManager -{ - public class JwtTokenHandler - { - public const string JWT_SECURITY_KEY = "_ll@v3Segur1d4d!123"; - private const int JWT_TOKEN_VALIDITY_MINS = 20; - - private readonly List _userLsist; - - public JwtTokenHandler() - { - _userLsist = new List - { - new UserAccount{UserName = "admin", Password = "admin123", Roles = new string [] { "MUJi4t5UCmA=", "LtMPr37abss=", } }, - new UserAccount{UserName = "user1", Password = "user1", Roles = new string [] { "nuepDLYs7n8=", "adnfaIJMvtc=" } }, - }; - } - - - public AuthResponse? GenerateJwtToken(AuthRequest authRequest) - { - if (string.IsNullOrWhiteSpace(authRequest.UserName) || string.IsNullOrWhiteSpace(authRequest.Password)) return null; - - // Validation - var userAcc = _userLsist.Where(x => x.UserName == authRequest.UserName && - x.Password == authRequest.Password).FirstOrDefault(); - - if (userAcc == null) return null; - - var tokenExpiryTimeStamp = DateTime.UtcNow.AddDays(JWT_TOKEN_VALIDITY_MINS); - //var tokenExpiryTimeStamp = DateTime.UtcNow.AddMinutes(JWT_TOKEN_VALIDITY_MINS); - var tokenKey = Encoding.ASCII.GetBytes(JWT_SECURITY_KEY); - - var claimsIdentity = new ClaimsIdentity(new List - { - new Claim(JwtRegisteredClaimNames.Name, authRequest.UserName), - }); - - foreach(var role in userAcc.Roles) - { - claimsIdentity.AddClaim(new Claim("permiso", role)); - } - - var signingCredentials = new SigningCredentials( - new SymmetricSecurityKey(tokenKey), - SecurityAlgorithms.HmacSha256Signature); - - var securityTokenDescriptor = new SecurityTokenDescriptor - { - Subject = claimsIdentity, - Expires = tokenExpiryTimeStamp, - SigningCredentials = signingCredentials - }; - - var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); - var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); - var token = jwtSecurityTokenHandler.WriteToken(securityToken); - - return new AuthResponse - { - UserName = userAcc.UserName, - ExpiresIn = (int)tokenExpiryTimeStamp.Subtract(DateTime.UtcNow).TotalSeconds, - JwtToken = token - }; - - - - } - - } -} diff --git a/JwtAuthManager/Models/AuthRequest.cs b/JwtAuthManager/Models/AuthRequest.cs deleted file mode 100644 index 2af324e..0000000 --- a/JwtAuthManager/Models/AuthRequest.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JwtAuthManager.Models -{ - public class AuthRequest - { - public string UserName { get; set; } - public string Password { get; set; } - } -} diff --git a/JwtAuthManager/Models/AuthResponse.cs b/JwtAuthManager/Models/AuthResponse.cs deleted file mode 100644 index 5551be0..0000000 --- a/JwtAuthManager/Models/AuthResponse.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JwtAuthManager.Models -{ - public class AuthResponse - { - public string UserName { get; set; } - public string JwtToken { get; set; } - public int ExpiresIn { get; set; } - } -} diff --git a/JwtAuthManager/Models/UserAccount.cs b/JwtAuthManager/Models/UserAccount.cs deleted file mode 100644 index 05ed833..0000000 --- a/JwtAuthManager/Models/UserAccount.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JwtAuthManager.Models -{ - public class UserAccount - { - public string UserName { get; set; } - public string Password { get; set; } - //public List Role { get; set; } - public string[] Roles { get; set; } - - } -} diff --git a/TestApi1/.config/dotnet-tools.json b/TestApi1/.config/dotnet-tools.json deleted file mode 100644 index b8c6c1f..0000000 --- a/TestApi1/.config/dotnet-tools.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "version": 1, - "isRoot": true, - "tools": { - "dotnet-ef": { - "version": "6.0.9", - "commands": [ - "dotnet-ef" - ] - } - } -} \ No newline at end of file diff --git a/TestApi1/Controllers/WeatherForecastController.cs b/TestApi1/Controllers/WeatherForecastController.cs deleted file mode 100644 index 1d47c99..0000000 --- a/TestApi1/Controllers/WeatherForecastController.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Microsoft.AspNetCore.Mvc; - -namespace TestApi1.Controllers -{ - [ApiController] - [Route("ApiTest")] - public class WeatherForecastController : ControllerBase - { - private static readonly string[] Summaries = new[] - { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; - - private readonly ILogger _logger; - - public WeatherForecastController(ILogger logger) - { - _logger = logger; - } - - [HttpGet(Name = "GetWeatherForecast")] - public IEnumerable Get() - { - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); - } - - [HttpPost] - public string post() - { - return "Ingresa al post"; - } - - [HttpDelete("{id}")] - public string delete(int id) - { - return "Elimina: "+ id; - } - } -} \ No newline at end of file diff --git a/TestApi1/Program.cs b/TestApi1/Program.cs deleted file mode 100644 index faa2d9c..0000000 --- a/TestApi1/Program.cs +++ /dev/null @@ -1,25 +0,0 @@ -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. - -builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - -var app = builder.Build(); - -// Configure the HTTP request pipeline. - app.UseSwagger(); - app.UseSwaggerUI(); -//if (app.Environment.IsDevelopment()) -//{ -//} - -//app.UseHttpsRedirection(); - -app.UseAuthorization(); - -app.MapControllers(); - -app.Run(); diff --git a/TestApi1/Properties/launchSettings.json b/TestApi1/Properties/launchSettings.json deleted file mode 100644 index 24ceeaf..0000000 --- a/TestApi1/Properties/launchSettings.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "profiles": { - "TestApi1": { - "commandName": "Project", - "launchBrowser": false, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "dotnetRunMessages": true, - "applicationUrl": "https://localhost:7041;http://localhost:5041" - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - }, - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:9982", - "sslPort": 44313 - } - } -} \ No newline at end of file diff --git a/TestApi1/TestApi1.csproj b/TestApi1/TestApi1.csproj deleted file mode 100644 index 60bf9ea..0000000 --- a/TestApi1/TestApi1.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - diff --git a/TestApi1/WeatherForecast.cs b/TestApi1/WeatherForecast.cs deleted file mode 100644 index 8d1e1b4..0000000 --- a/TestApi1/WeatherForecast.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace TestApi1 -{ - public class WeatherForecast - { - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string? Summary { get; set; } - } -} \ No newline at end of file diff --git a/TestApi1/appsettings.Development.json b/TestApi1/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/TestApi1/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/TestApi1/appsettings.json b/TestApi1/appsettings.json deleted file mode 100644 index 10f68b8..0000000 --- a/TestApi1/appsettings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/TestApi2/.config/dotnet-tools.json b/TestApi2/.config/dotnet-tools.json deleted file mode 100644 index b8c6c1f..0000000 --- a/TestApi2/.config/dotnet-tools.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "version": 1, - "isRoot": true, - "tools": { - "dotnet-ef": { - "version": "6.0.9", - "commands": [ - "dotnet-ef" - ] - } - } -} \ No newline at end of file diff --git a/TestApi2/Controllers/ContratosController.cs b/TestApi2/Controllers/ContratosController.cs deleted file mode 100644 index 5381b2d..0000000 --- a/TestApi2/Controllers/ContratosController.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; - -namespace TestApi2.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class ContratosController : ControllerBase - { - - // Admin: Consulta (1) Crear (0) - // Doctor: Permiso 1, 0 - [HttpGet] - //[Authorize(Roles = "Doctor,admin")] - public string get() - { - return "Get Contratos Admin y user"; - } - - [HttpPost] - //[Authorize(Roles = "Admin")] - public string post() - { - return "POST Contratos Solo ADMIN"; - } - } -} diff --git a/TestApi2/Controllers/WeatherForecastController.cs b/TestApi2/Controllers/WeatherForecastController.cs deleted file mode 100644 index 02508c7..0000000 --- a/TestApi2/Controllers/WeatherForecastController.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Microsoft.AspNetCore.Mvc; - -namespace TestApi2.Controllers -{ - [ApiController] - [Route("ApiTest")] - public class WeatherForecastController : ControllerBase - { - private static readonly string[] Summaries = new[] - { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; - - private readonly ILogger _logger; - - public WeatherForecastController(ILogger logger) - { - _logger = logger; - } - - [HttpGet(Name = "GetWeatherForecast")] - public IEnumerable Get() - { - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); - } - - [HttpPost] - public string post() - { - return "Ingresa al post"; - } - - [HttpDelete("{id}")] - public string delete(int id) - { - return "Elimina: " + id; - } - } -} \ No newline at end of file diff --git a/TestApi2/Program.cs b/TestApi2/Program.cs deleted file mode 100644 index 6a5f708..0000000 --- a/TestApi2/Program.cs +++ /dev/null @@ -1,28 +0,0 @@ -using JwtAuthManager; - -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. - -builder.Services.AddControllers(); -builder.Services.AddCustomJwtAuthentication(); // <========= - -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - -var app = builder.Build(); - -// Configure the HTTP request pipeline. - app.UseSwagger(); - app.UseSwaggerUI(); -//if (app.Environment.IsDevelopment()) -//{ -//} - -app.UseAuthentication(); // <========= -app.UseAuthorization(); - -app.MapControllers(); - -app.Run(); diff --git a/TestApi2/Properties/launchSettings.json b/TestApi2/Properties/launchSettings.json deleted file mode 100644 index 758f3f1..0000000 --- a/TestApi2/Properties/launchSettings.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "profiles": { - "TestApi2": { - "commandName": "Project", - "launchBrowser": false, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "dotnetRunMessages": true, - "applicationUrl": "http://localhost:5102" - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - }, - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:22994", - "sslPort": 0 - } - } -} \ No newline at end of file diff --git a/TestApi2/TestApi2.csproj b/TestApi2/TestApi2.csproj deleted file mode 100644 index 2b222da..0000000 --- a/TestApi2/TestApi2.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - diff --git a/TestApi2/WeatherForecast.cs b/TestApi2/WeatherForecast.cs deleted file mode 100644 index 4cb7e49..0000000 --- a/TestApi2/WeatherForecast.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace TestApi2 -{ - public class WeatherForecast - { - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string? Summary { get; set; } - } -} \ No newline at end of file diff --git a/TestApi2/appsettings.Development.json b/TestApi2/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/TestApi2/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/TestApi2/appsettings.json b/TestApi2/appsettings.json deleted file mode 100644 index 10f68b8..0000000 --- a/TestApi2/appsettings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" -}