Limpieza de código y dependencias obsoletas

This commit is contained in:
luismd98 2022-11-02 12:06:54 -05:00
parent c44014b458
commit c750ae7f0f
38 changed files with 44 additions and 961 deletions

View File

@ -29,7 +29,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Auth\Auth.csproj" /> <ProjectReference Include="..\Auth\Auth.csproj" />
<ProjectReference Include="..\JwtAuthManager\JwtAuthManager.csproj" />
</ItemGroup> </ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties routes_4ocelot_1contratos_1json__JsonSchema="https://json.schemastore.org/ocelot.json" routes_4ocelot_1global_1json__JsonSchema="https://json.schemastore.org/ocelot.json" routes_4ocelot_1swaggerendpoints_1json__JsonSchema="https://json.schemastore.org/ocelot.json" /></VisualStudio></ProjectExtensions> <ProjectExtensions><VisualStudio><UserProperties routes_4ocelot_1contratos_1json__JsonSchema="https://json.schemastore.org/ocelot.json" routes_4ocelot_1global_1json__JsonSchema="https://json.schemastore.org/ocelot.json" routes_4ocelot_1swaggerendpoints_1json__JsonSchema="https://json.schemastore.org/ocelot.json" /></VisualStudio></ProjectExtensions>

View File

@ -1,5 +1,4 @@
using JwtAuthManager; using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens;
using Ocelot.Configuration; using Ocelot.Configuration;
using Ocelot.Middleware; using Ocelot.Middleware;
using Security; using Security;
@ -18,20 +17,18 @@ namespace ApiGateway
public static bool Authorize(HttpContext ctx) public static bool Authorize(HttpContext ctx)
{ {
// Solo para test // Solo para test
string seguimiento = ctx.Request.Headers["Potato"]; //string seguimiento = ctx.Request.Headers["Potato"];
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 calledUrl = ctx.Items.DownstreamRoute().UpstreamPathTemplate.OriginalValue;
var isLogin = calledUrl == "/Ext/Login" ;
var isExtLogin = calledUrl == "/Auth/Login"; string calledUrl = ctx.Items.DownstreamRoute().UpstreamPathTemplate.OriginalValue;
// Excepcion para login, no requiere token // Excepcion para login, no requiere token
if (String.Equals(calledUrl, "/Ext/Login") || if (String.Equals(calledUrl, "/Ext/Login") ||
String.Equals(calledUrl, "/Auth/Login")) String.Equals(calledUrl, "/Auth/Login"))
return true; return true;
//if (isLogin == true || isExtLogin == true) return true;
try try
{ {
@ -44,11 +41,11 @@ namespace ApiGateway
signature = Base64Decode(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 ", "")); 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); var jwtToken = new JwtSecurityToken(jwtDescifrado);
@ -57,12 +54,10 @@ namespace ApiGateway
//Claims dentro del .json //Claims dentro del .json
DownstreamRoute? route = (DownstreamRoute?)ctx.Items["DownstreamRoute"]; 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; 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 //Claims del token
Claim[] claims = jwtToken.Claims.ToArray<Claim>(); Claim[] claims = jwtToken.Claims.ToArray<Claim>();
@ -113,26 +108,19 @@ namespace ApiGateway
} }
//Si no hay perfil seleccionado //Si no hay perfil seleccionado
if (signature.IsNullOrEmpty()) if (String.IsNullOrEmpty(signature))
throw new Exception("Falta el perfil, no mames"); throw new Exception("Falta el perfil, no mames");
bool aplicaRolSeleccionado = rolesLst.Any(signature!.Contains); bool aplicaRolSeleccionado = rolesLst.Any(signature!.Contains);
//Aqui remuevo los :: teniendo en cuenta key == permisos cl.Value //Aqui remuevo los :: teniendo en cuenta key == permisos cl.Value
//if (cl.Value == m.Value)
if (String.Equals(newPermiso, m.Value) && aplicaRolSeleccionado == true) if (String.Equals(newPermiso, m.Value) && aplicaRolSeleccionado == true)
{ {
return true; return true;
//cont++; //NO NECESARIO porque solo hay 1 permiso por request
} }
} }
} }
} }
//if (cont == matchesand.Count)
//{
// return true;
// // break;
//}
} }
} }
return false; return false;
@ -142,11 +130,6 @@ namespace ApiGateway
ctx.Items.SetError(new UnauthenticatedError(e.Message)); ctx.Items.SetError(new UnauthenticatedError(e.Message));
return false; return false;
} }
///
//return true;
///
} }
@ -159,12 +142,11 @@ namespace ApiGateway
ValidateIssuer = false, ValidateIssuer = false,
ValidateAudience = false, ValidateAudience = false,
ValidateIssuerSigningKey = true, 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(); var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken validatedToken = null; SecurityToken? validatedToken = null;
try try
{ {
@ -184,7 +166,7 @@ namespace ApiGateway
return false; return false;
//throw; //throw;
} }
//... manual validations return false if anything untoward is discovered //... Si el token es invalido (=null) devuelve false
return validatedToken != null; return validatedToken != null;
} }
@ -194,7 +176,8 @@ namespace ApiGateway
try try
{ {
string? b64Decrypted = Base64Decode(value); string? b64Decrypted = Base64Decode(value);
if (b64Decrypted.IsNullOrEmpty()) return null;
if (String.IsNullOrEmpty(b64Decrypted)) return null;
string decryptedText = ""; string decryptedText = "";
for (int i = 0; i < b64Decrypted!.Length; i++) for (int i = 0; i < b64Decrypted!.Length; i++)

View File

@ -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<string>(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<string>(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<T>(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<string> SplitCsv(string csvList, bool nullOrWhitespaceInputReturnsNull = false)
//{
// if (string.IsNullOrWhiteSpace(csvList))
// return nullOrWhitespaceInputReturnsNull ? null : new List<string>();
// return csvList
// .TrimEnd(',')
// .Split(',')
// .AsEnumerable<string>()
// .Select(s => s.Trim())
// .ToList();
//}
//public bool IsNullOrWhitespace(string s)
//{
// return String.IsNullOrWhiteSpace(s);
//}
}
}

View File

@ -1,25 +1,23 @@
using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Ocelot.Middleware; using Ocelot.Middleware;
using Ocelot.RequestId;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net; using System.Net;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Net.Http.Headers;
namespace ApiGateway namespace ApiGateway.Middleware
{ {
public class OcelotJwtMiddleware : OcelotPipelineConfiguration public class OcelotJwtMiddleware : OcelotPipelineConfiguration
{ {
private static readonly string RoleSeparator = ","; private static readonly string RoleSeparator = ",";
/*
Nota: No tengo ni idea de por qué este método es necesario, pero hace que funcione...
*/
public OcelotJwtMiddleware() public OcelotJwtMiddleware()
{ {
PreAuthorizationMiddleware = async (ctx, next) => PreAuthorizationMiddleware = async (ctx, next) =>
@ -28,7 +26,7 @@ namespace ApiGateway
}; };
} }
public async Task ProcessRequest(HttpContext context, System.Func<Task> next) public async Task ProcessRequest(HttpContext context, Func<Task> next)
{ {
//var _bearer_token = context.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", ""); //var _bearer_token = context.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", "");
@ -41,10 +39,10 @@ namespace ApiGateway
var logger = loggerFactory.CreateLogger(""); var logger = loggerFactory.CreateLogger("");
logger.LogInformation("Potato 3"); //logger.LogInformation("Potato 3");
logger.LogInformation("Bearer:"); //logger.LogInformation("Bearer:");
logger.LogInformation(_bearer_token); //logger.LogInformation(_bearer_token);
logger.LogDebug("Potato 4"); //logger.LogDebug("Potato 4");
// Get the the any service object, if required // Get the the any service object, if required
//var anyService = context.RequestServices.GetService(typeof(<Service class reference>)); //var anyService = context.RequestServices.GetService(typeof(<Service class reference>));
@ -78,33 +76,5 @@ namespace ApiGateway
await context.Response.WriteAsync(msg); await context.Response.WriteAsync(msg);
} }
//public static Func< DownstreamContext, Func<Task>, 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<UserToken>(jwtToken);
// if (decodedObject != null)
// {
// return downStreamContext.DownstreamReRoute.RouteClaimsRequirement["Role"]
// ?.Split(RoleSeparator)
// .FirstOrDefault(role => role.Trim() == decodedObject.GetRole()) != default;
// }
// return false;
//}
} }
} }

View File

@ -3,18 +3,9 @@ using Ocelot.Logging;
using Ocelot.Middleware; using Ocelot.Middleware;
using Ocelot.Responder; using Ocelot.Responder;
namespace ApiGateway.Middleware
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
{ {
public class OcelotResponseMiddleware : Ocelot.Middleware.OcelotMiddleware public class OcelotResponseMiddleware : OcelotMiddleware
{ {
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
private readonly IHttpResponder _responder; private readonly IHttpResponder _responder;
@ -34,7 +25,6 @@ namespace ApiGateway
public async Task Invoke(HttpContext httpContext) public async Task Invoke(HttpContext httpContext)
{ {
//var x = CustomLogic.Authorize(httpContext);
await _next.Invoke(httpContext); await _next.Invoke(httpContext);
if (httpContext.Response.HasStarted) if (httpContext.Response.HasStarted)

View File

@ -1,14 +1,11 @@
using ApiGateway; using ApiGateway;
using JwtAuthManager;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
using Ocelot.Authorization;
using Ocelot.DependencyInjection; using Ocelot.DependencyInjection;
using Ocelot.Middleware; using Ocelot.Middleware;
using MMLib.SwaggerForOcelot.DependencyInjection; using MMLib.SwaggerForOcelot.DependencyInjection;
using Ocelot.Provider.Polly; using Ocelot.Provider.Polly;
using ApiGateway.Config; using ApiGateway.Config;
using System.Net; using ApiGateway.Middleware;
using Microsoft.AspNetCore.Http;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -31,23 +28,11 @@ var pipeConfig = new OcelotPipelineConfiguration
AuthorizationMiddleware = async (downStreamContext, next) => AuthorizationMiddleware = async (downStreamContext, next) =>
{ {
//Authorize(downStreamContext);
var _bearer_token = downStreamContext.Request.Headers[HeaderNames.Authorization].ToString(); var _bearer_token = downStreamContext.Request.Headers[HeaderNames.Authorization].ToString();
logger.LogInformation("Bearer :");
logger.LogInformation("Bearer 2:");
logger.LogInformation(_bearer_token); 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); bool isAuthorized = CustomLogic.Authorize(downStreamContext);
if (isAuthorized) if (isAuthorized)
{ {
@ -74,7 +59,7 @@ builder.Services.AddCors(options =>
builder.Services.AddOcelot(builder.Configuration).AddPolly(); builder.Services.AddOcelot(builder.Configuration).AddPolly();
builder.Services.AddSwaggerForOcelot(builder.Configuration); builder.Services.AddSwaggerForOcelot(builder.Configuration);
builder.Services.AddCustomJwtAuthentication(); //builder.Services.AddCustomJwtAuthentication();
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
@ -100,15 +85,10 @@ builder.Services.AddAuthentication();
var app = builder.Build(); var app = builder.Build();
app.UseCors("MyCors"); app.UseCors("MyCors");
//app.UseCors("widthoutCors");
app.UseSwagger(); app.UseSwagger();
//Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
//{
//}
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
Environment.SetEnvironmentVariable("Mode", "Dev"); Environment.SetEnvironmentVariable("Mode", "Dev");
@ -119,9 +99,6 @@ else
} }
//IApplicationBuilder config2 = new IApplicationBuilder
// Cargue de Ocelot // Cargue de Ocelot
app.UseMiddleware<OcelotResponseMiddleware>(); app.UseMiddleware<OcelotResponseMiddleware>();
app.UseSwaggerForOcelotUI(options => app.UseSwaggerForOcelotUI(options =>

View File

@ -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
}
}
}

View File

@ -1,19 +0,0 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/ApiTest",
"UpstreamHttpMethod": [ "GET", "POST" ],
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
"Host": "localhost",
"Port" : 7041
]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:7041"
}
}

View File

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\JwtAuthManager\JwtAuthManager.csproj" />
</ItemGroup>
</Project>

View File

@ -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<AuthResponse?> 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
}
}

View File

@ -1,18 +0,0 @@
using JwtAuthManager;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSingleton<JwtTokenHandler>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -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
}
}
}

View File

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

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

View File

@ -7,12 +7,14 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApiGateway", "ApiGateway",
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "ApiGateway\ApiGateway.csproj", "{AC631810-7FAF-4C9A-A35D-3EC538A49810}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "ApiGateway\ApiGateway.csproj", "{AC631810-7FAF-4C9A-A35D-3EC538A49810}"
EndProject 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}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Auth", "Auth\Auth.csproj", "{76522272-9D28-4168-8296-AFC933D22650}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegradorBE", "IntegradorBE\IntegradorBE.csproj", "{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegradorBE", "IntegradorBE\IntegradorBE.csproj", "{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}"
EndProject 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 Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU 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}.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.ActiveCfg = Release|Any CPU
{AC631810-7FAF-4C9A-A35D-3EC538A49810}.Release|Any CPU.Build.0 = 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.ActiveCfg = Debug|Any CPU
{76522272-9D28-4168-8296-AFC933D22650}.Debug|Any CPU.Build.0 = 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 {76522272-9D28-4168-8296-AFC933D22650}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -41,6 +39,8 @@ Global
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution GlobalSection(NestedProjects) = preSolution
{AC631810-7FAF-4C9A-A35D-3EC538A49810} = {9F5D8D1C-CF99-4BDD-8497-0123656B8A48} {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 EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EC576D5A-ADE3-40CC-BF55-7E52E6F18AC4} SolutionGuid = {EC576D5A-ADE3-40CC-BF55-7E52E6F18AC4}

View File

@ -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<CustomJwtAuthExtension> _logger;
//public CustomJwtAuthExtension(ILogger<> logger)
//{
// _logger = (ILogger<CustomJwtAuthExtension>?)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))
};
});
}
}
}

View File

@ -1,16 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.9" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.23.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.23.1" />
</ItemGroup>
</Project>

View File

@ -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<UserAccount> _userLsist;
public JwtTokenHandler()
{
_userLsist = new List<UserAccount>
{
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<Claim>
{
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
};
}
}
}

View File

@ -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; }
}
}

View File

@ -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; }
}
}

View File

@ -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<string> Role { get; set; }
public string[] Roles { get; set; }
}
}

View File

@ -1,12 +0,0 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "6.0.9",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@ -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<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> 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;
}
}
}

View File

@ -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();

View File

@ -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
}
}
}

View File

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
</Project>

View File

@ -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; }
}
}

View File

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

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

View File

@ -1,12 +0,0 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "6.0.9",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@ -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";
}
}
}

View File

@ -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<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> 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;
}
}
}

View File

@ -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();

View File

@ -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
}
}
}

View File

@ -1,17 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JwtAuthManager\JwtAuthManager.csproj" />
</ItemGroup>
</Project>

View File

@ -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; }
}
}

View File

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

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