Primer commit

This commit is contained in:
luismd98 2022-11-02 11:31:23 -05:00
commit c44014b458
67 changed files with 3371 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

363
.gitignore vendored Normal file
View File

@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

View File

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

View File

@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Trash\**" />
<Content Remove="Trash\**" />
<EmbeddedResource Remove="Trash\**" />
<None Remove="Trash\**" />
</ItemGroup>
<ItemGroup>
<Content Remove="Routes\ocelot.apitest.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Filter" Version="1.1.2" />
<PackageReference Include="MMLib.SwaggerForOcelot" Version="5.2.0" />
<PackageReference Include="Ocelot" Version="18.0.0" />
<PackageReference Include="Ocelot.Provider.Polly" Version="18.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Auth\Auth.csproj" />
<ProjectReference Include="..\JwtAuthManager\JwtAuthManager.csproj" />
</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>
</Project>

View File

@ -0,0 +1,15 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ApiGateway.Config
{
public class AlterUpstream
{
public static string AlterUpstreamSwaggerJson(HttpContext context, string swaggerJson)
{
var swagger = JObject.Parse(swaggerJson);
// ... alter upstream json
return swagger.ToString(Formatting.Indented);
}
}
}

228
ApiGateway/CustomLogic.cs Normal file
View File

@ -0,0 +1,228 @@
using JwtAuthManager;
using Microsoft.IdentityModel.Tokens;
using Ocelot.Configuration;
using Ocelot.Middleware;
using Security;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.RegularExpressions;
namespace ApiGateway
{
public static class CustomLogic
{
//private static readonly int _SEMILLA = 1262;
private static readonly Encripter _encript = new();
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;
var isLogin = calledUrl == "/Ext/Login" ;
var isExtLogin = calledUrl == "/Auth/Login";
// 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
{
string path = ctx.Request.Path;
string authString = ctx.Request.Headers["Authorization"];
//Perfil seleccionado, no obligatorio para login
string? signature = ctx.Request.Headers["Signature"];
signature = Base64Decode(signature);
if (authString.IsNullOrEmpty()) 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");
var jwtToken = new JwtSecurityToken(jwtDescifrado);
if (VerifyToken(jwtToken.RawData) == false) throw new Exception("Firma inválida");
//Claims dentro del .json
DownstreamRoute? route = (DownstreamRoute?)ctx.Items["DownstreamRoute"];
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<Claim>();
//where are stored the required claims for the route
Dictionary<string, string> required = route.RouteClaimsRequirement;
Regex reor = new Regex(@"[^,\s+$ ][^\,]*[^,\s+$ ]");
MatchCollection matches;
Regex reand = new Regex(@"[^&\s+$ ][^\&]*[^&\s+$ ]");
MatchCollection matchesand;
//int cont = 0;
foreach (KeyValuePair<string, string> claim in required)
{
matches = reor.Matches(claim.Value);
foreach (Match match in matches)
{
matchesand = reand.Matches(match.Value);
//cont = 0;
foreach (Match m in matchesand) //m = claim dentro dle json (value)
{
//Si permite cualquier permiso
if (String.Equals("any", m.Value)) return true;
foreach (Claim cl in claims) // Claim (key:value) desde el token
{
if (cl.Type == claim.Key && String.Equals(claim.Key, "permisos"))
{
string separador = "::";
int index = cl.Value.LastIndexOf(separador);
string newPermiso = cl.Value;
string permisoRoles = cl.Value;
if (index >= 0)
newPermiso = cl.Value[..index];
permisoRoles = cl.Value.Substring(index + separador.Length);
var rolesLst = permisoRoles.Split(',');
// Excepcion de rol Seleccionado para Externo
if(String.Equals(newPermiso, m.Value) &&
String.Equals(_encript.DecryptHashTkn(newPermiso), "externo"))
{
return true;
}
//Si no hay perfil seleccionado
if (signature.IsNullOrEmpty())
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;
}
catch (Exception e)
{
ctx.Items.SetError(new UnauthenticatedError(e.Message));
return false;
}
///
//return true;
///
}
public static bool VerifyToken(string token)
{
if(_encript.IsValid == false) return false;
var validationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
//IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtTokenHandler.JWT_SECURITY_KEY))
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Encripter.HashKey))
};
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken validatedToken = null;
try
{
tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
}
catch (SecurityTokenException)
{
return false;
}
catch (Exception e)
{
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
var logger = loggerFactory.CreateLogger("");
//something else happened
logger.LogInformation(e.ToString());
return false;
//throw;
}
//... manual validations return false if anything untoward is discovered
return validatedToken != null;
}
public static string? DesCifrar(string value)
{
if (_encript.IsValid == false) return null;
try
{
string? b64Decrypted = Base64Decode(value);
if (b64Decrypted.IsNullOrEmpty()) return null;
string decryptedText = "";
for (int i = 0; i < b64Decrypted!.Length; i++)
{
int encrypted = (int)b64Decrypted[i];
int decryption = encrypted - _encript.getSemilla();
decryptedText += Char.ConvertFromUtf32(decryption);
}
return decryptedText;
}
catch (Exception)
{
return null;
}
}
public static string? Base64Decode(string base64EncodedData)
{
try
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
catch (Exception)
{
return null;
}
}
}
}

73
ApiGateway/Loggin.cs Normal file
View File

@ -0,0 +1,73 @@
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

@ -0,0 +1,110 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
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
{
public class OcelotJwtMiddleware : OcelotPipelineConfiguration
{
private static readonly string RoleSeparator = ",";
public OcelotJwtMiddleware()
{
PreAuthorizationMiddleware = async (ctx, next) =>
{
await ProcessRequest(ctx, next);
};
}
public async Task ProcessRequest(HttpContext context, System.Func<Task> next)
{
//var _bearer_token = context.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", "");
context.Request.Headers[HeaderNames.Authorization] = "Reemplazo el token";
var _bearer_token = context.Request.Headers[HeaderNames.Authorization].ToString();
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddDebug());
var logger = loggerFactory.CreateLogger("");
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(<Service class reference>));
var user = ((DefaultHttpContext)context)?.User;
var email = user.Claims.Where(y => y.Type.Contains("email")).FirstOrDefault()?.Value;
if (!string.IsNullOrWhiteSpace(email) && email.Equals("BobSmith66@email.com", StringComparison.CurrentCultureIgnoreCase))
{
// Example 1 : adding extra claims
EnrichClaim(user);
}
// Call the underline service
await next.Invoke();
}
private void EnrichClaim(ClaimsPrincipal claims)
{
var listOfClaims = new List<Claim>
{
new Claim("CustomClaimName", "CustomClaimValue")
};
claims.AddIdentity(new ClaimsIdentity(listOfClaims));
}
private static async Task ReturnStatus(HttpContext context, HttpStatusCode statusCode, string msg)
{
context.Response.StatusCode = (int)statusCode;
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

@ -0,0 +1,67 @@
using Ocelot.Infrastructure.Extensions;
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
{
public class OcelotResponseMiddleware : Ocelot.Middleware.OcelotMiddleware
{
private readonly RequestDelegate _next;
private readonly IHttpResponder _responder;
private readonly IErrorsToHttpStatusCodeMapper _codeMapper;
public OcelotResponseMiddleware(
RequestDelegate next,
IHttpResponder responder,
IErrorsToHttpStatusCodeMapper codeMapper,
IOcelotLoggerFactory loggerFactory)
: base(loggerFactory.CreateLogger<OcelotResponseMiddleware>())
{
_next = next;
_responder = responder;
_codeMapper = codeMapper;
}
public async Task Invoke(HttpContext httpContext)
{
//var x = CustomLogic.Authorize(httpContext);
await _next.Invoke(httpContext);
if (httpContext.Response.HasStarted)
return;
var errors = httpContext.Items.Errors();
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}");
var statusCode = _codeMapper.Map(errors);
var error = string.Join(",", errors.Select(x => x.Message));
httpContext.Response.StatusCode = statusCode;
// output error
await httpContext.Response.WriteAsync(error);
}
else
{
Logger.LogDebug("no pipeline errors, setting and returning completed response");
var downstreamResponse = httpContext.Items.DownstreamResponse();
await _responder.SetResponseOnHttpContext(httpContext, downstreamResponse);
}
}
}
}

145
ApiGateway/Program.cs Normal file
View File

@ -0,0 +1,145 @@
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;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddOcelotWithSwaggerSupport(options =>
{
options.Folder = "Routes";
});
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
var logger = loggerFactory.CreateLogger("");
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
var pipeConfig = new OcelotPipelineConfiguration
{
AuthorizationMiddleware = async (downStreamContext, next) =>
{
//Authorize(downStreamContext);
var _bearer_token = downStreamContext.Request.Headers[HeaderNames.Authorization].ToString();
logger.LogInformation("Bearer 2:");
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)
{
await next.Invoke();
}
else
{
//downStreamContext.Items.SetError(new UnauthenticatedError("Nel wey, no estas autorizado"));
return;
}
}
};
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "MyCors", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
builder.Services.AddOcelot(builder.Configuration).AddPolly();
builder.Services.AddSwaggerForOcelot(builder.Configuration);
builder.Services.AddCustomJwtAuthentication();
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
builder.Configuration.SetBasePath(Directory.GetCurrentDirectory())
.AddOcelot("Routes", builder.Environment)
.AddEnvironmentVariables();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// Swagger for ocelot
builder.Services.AddSwaggerGen();
builder.Services.AddAuthorization();
builder.Services.AddAuthentication();
var app = builder.Build();
app.UseCors("MyCors");
//app.UseCors("widthoutCors");
app.UseSwagger();
//Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
//{
//}
if (app.Environment.IsDevelopment())
{
Environment.SetEnvironmentVariable("Mode", "Dev");
}
else
{
Environment.SetEnvironmentVariable("Mode", "Prod");
}
//IApplicationBuilder config2 = new IApplicationBuilder
// Cargue de Ocelot
app.UseMiddleware<OcelotResponseMiddleware>();
app.UseSwaggerForOcelotUI(options =>
{
options.PathToSwaggerGenerator = "/swagger/docs";
options.ReConfigureUpstreamSwaggerJson = AlterUpstream.AlterUpstreamSwaggerJson;
}).UseOcelot(pipeConfig).Wait();
app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();
app.MapGet("/", () => "Hello World!");
app.Run();

View File

@ -0,0 +1,31 @@
{
"profiles": {
"ApiGateway": {
"commandName": "Project",
"launchBrowser": false,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"MySecretKey": "_ll@v3Segur1d4d!123"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5042"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
},
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:9939",
"sslPort": 0
}
}
}

View File

@ -0,0 +1,88 @@
{
"SwaggerEndPoints": [
{
"Key": "ApiGetway",
"TransformByOcelotConfig": false,
"Config": [
{
"Name": "ApiGetway",
"Version": "1.0",
"Url": "http://localhost:80/api/swagger/v1/swagger.json"
}
]
},
{
"Key": "DatosMaestros",
"TransformByOcelotConfig": true,
"Config": [
{
"Name": "DatosMaestros",
"Version": "1.0",
"Url": "http://localhost:8146/swagger/v1/swagger.json"
}
]
},
{
"Key": "MsAdminUsuarios",
"TransformByOcelotConfig": true,
"Config": [
{
"Name": "MsAdminUsuarios",
"Version": "1.0",
"Url": "http://localhost:8151/swagger/v1/swagger.json"
}
]
},
{
"Key": "Afiliados",
"TransformByOcelotConfig": true,
"Config": [
{
"Name": "Afiliados",
"Version": "1.0",
"Url": "http://localhost:8145/swagger/v1/swagger.json"
}
]
},
{
"Key": "Externo",
"TransformByOcelotConfig": true,
"Config": [
{
"Name": "Externo",
"Version": "1.0",
"Url": "http://localhost:8199/swagger/v1/swagger.json"
}
]
}
//{
// "Key": "MsContratos",
// "TransformByOcelotConfig": true,
// "Config": [
// {
// "Name": "MsContratos",
// "Version": "1.0",
// "Url": "http://localhost:5102/swagger/v1/swagger.json"
// }
// ]
//},
//{
// "Key": "apitest",
// "TransformByOcelotConfig": true,
// "Config": [
// {
// "Name": "ApiTest",
// "Version": "1.0",
// "Url": "http://localhost:5041/swagger/v1/swagger.json"
// }
// ]
]
}

View File

@ -0,0 +1,319 @@
{
"Routes": [
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Auth/Login",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/Auth/Login",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Microservicios",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/Microservicios",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Microservicios",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/Microservicios",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Perfiles",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/Perfiles",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Perfiles",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/Perfiles",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Perfiles",
"UpstreamHttpMethod": [ "PATCH" ],
"DownstreamPathTemplate": "/Perfiles",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Permisos",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/Permisos",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Permisos",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/Permisos",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/PerfilesPorUsuario",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/PerfilesPorUsuario",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/PerfilesPorUsuario",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/PerfilesPorUsuario",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Usuarios/Iniciales",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/Usuarios/Iniciales",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Usuarios",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/Usuarios",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Usuarios",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/Usuarios",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/Usuarios",
"UpstreamHttpMethod": [ "PATCH" ],
"DownstreamPathTemplate": "/Usuarios",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "MsAdminUsuarios",
"UpstreamPathTemplate": "/TESTERROR",
"UpstreamHttpMethod": [ "PATCH" ],
"DownstreamPathTemplate": "/Usuarios/TESTERROR",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8151
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
}
]
}

View File

@ -0,0 +1,306 @@
{
"Routes": [
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/Afiliados",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados",
"UpstreamHttpMethod": [ "Post" ],
"DownstreamPathTemplate": "/Afiliados",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/Documento",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/Afiliados/Documento",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/Aceptar",
"UpstreamHttpMethod": [ "Post" ],
"DownstreamPathTemplate": "/Afiliados/Aceptar",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/SubirSoporte",
"UpstreamHttpMethod": [ "Post" ],
"DownstreamPathTemplate": "/Afiliados/SubirSoporte",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/CheckDocumento",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/Afiliados/CheckDocumento",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/Rechazar",
"UpstreamHttpMethod": [ "Post" ],
"DownstreamPathTemplate": "/Afiliados/Rechazar",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/Aprobar",
"UpstreamHttpMethod": [ "Post" ],
"DownstreamPathTemplate": "/Afiliados/Aprobar",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/Generar",
"UpstreamHttpMethod": [ "Patch" ],
"DownstreamPathTemplate": "/Afiliados/Generar",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Afiliados/AfiliadosUsuario",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/Afiliados/AfiliadosUsuario",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/Archivos",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/Archivos",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/DeclaratoriasPorAfiliado",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/DeclaratoriasPorAfiliado",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/PreguntasDeclaratorias",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/PreguntasDeclaratorias",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/UPCAdicional",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/UPCAdicional",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/UPCAdicional",
"UpstreamHttpMethod": [ "Post" ],
"DownstreamPathTemplate": "/UPCAdicional",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
},
{
"SwaggerKey": "Afiliados",
"UpstreamPathTemplate": "/UPCAdicional",
"UpstreamHttpMethod": [ "Patch" ],
"DownstreamPathTemplate": "/UPCAdicional",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8145
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
}
]
}

View File

@ -0,0 +1,56 @@
{
"Routes": [
{
"SwaggerKey": "apitest",
//Incoming
"UpstreamPathTemplate": "/Test",
"UpstreamHttpMethod": [ "GET", "POST" ],
//Routed
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5041
}
],
"DownstreamPathTemplate": "/ApiTest",
//Auth
"AuthenticationOptions": {
//"AuthenticationProviderKey": "Bearer",
"AllowedScopes": [] // Ejemplo: "api.portfolio.manager.v1"
},
"RouteClaimsRequirement": {
"permisos": "nuepDLYs7n8="
}
},
{
"SwaggerKey": "apitest",
"UpstreamPathTemplate": "/Test/{id}",
"UpstreamHttpMethod": [ "DELETE" ],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5041
}
],
"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
}
}
]
}

View File

@ -0,0 +1,45 @@
{
"Routes": [
{
"SwaggerKey": "MsContratos",
//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"
//}
},
{
"SwaggerKey": "MsContratos",
//Incoming
"UpstreamPathTemplate": "/Contratos/asdasd/potato",
"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"
//}
}
]
}

View File

@ -0,0 +1,23 @@
{
"Routes": [
{
"SwaggerKey": "DatosMaestros",
"UpstreamPathTemplate": "/DatosMaestros",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/DatosMaestros",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8146
}
],
"RouteClaimsRequirement": {
"permisos": "any"
}
}
]
}

View File

@ -0,0 +1,39 @@
{
"Routes": [
{
"SwaggerKey": "Externo",
"UpstreamPathTemplate": "/Ext/Login",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/Auth/Login",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8199
}
]
},
{
"SwaggerKey": "Externo",
"UpstreamPathTemplate": "/UPC",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/UPC",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8199
}
],
"RouteClaimsRequirement": {
"permisos": "W3Y9E3ioiao="
//"permisos": "8IF4fbgkEP0=" // => Dev
}
}
]
}

View File

@ -0,0 +1,9 @@
{
"GlobalConfiguration": {
//"BaseUrl": "https://localhost:8021",
"RateLimitOptions": {
"QuotaExceededMessage": "Request excedidos",
"HttpStatusCode": 909 //429 default
}
}
}

View File

@ -0,0 +1,105 @@
{
"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

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

View File

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

View File

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

1
ApiGateway/ocelot.json Normal file

File diff suppressed because one or more lines are too long

13
Auth/Auth.csproj Normal file
View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RawScape.Nini" Version="1.0.0" />
</ItemGroup>
</Project>

179
Auth/Security.cs Normal file
View File

@ -0,0 +1,179 @@
using Nini.Config;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace Security
{
public class Encripter
{
public static int _SEMILLA { get; private set; } = -1;
public static string? HashKey { get; private set; }
private static string? PwdKey { get; set; }
public Encripter()
{
string? mode = Environment.GetEnvironmentVariable("Mode");
if (mode == "Prod")
{
ReadCredentials();
}
else
{
string DevKey = Environment.GetEnvironmentVariable("MySecretKey")!;
HashKey = DevKey;
PwdKey = DevKey;
_SEMILLA = 1262;
}
}
public bool IsValid
{
get
{
return HashKey != null && PwdKey != null && _SEMILLA != -1;
}
}
public int getSemilla()
{
return _SEMILLA;
}
private void ReadCredentials()
{
try
{
//var folder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var filePath = Path.Combine("C:\\Users\\Administrator", ".hims", "info");
//var filePath = Path.Combine("C:\\Users\\Admin\\Desktop\\sqsas\\usuarios", "info");
//Validacion manual antes de leer
if (!File.Exists(filePath)) //Exist = false
{
//Devolver error
HashKey = null;
PwdKey = null;
_SEMILLA = -1;
return;
}
IConfigSource source = new IniConfigSource(filePath);
var security = source.Configs["hash"];
var defecto = source.Configs["default"];
HashKey = security.Get("tkn_key");
PwdKey = security.Get("hash_key");
_SEMILLA = Int32.Parse(defecto.Get("seed"));
Console.WriteLine();
}
catch (IOException ioEx)
{
Console.WriteLine(ioEx.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public string EncryptPwd(string text)
{
return Encrypt(text, PwdKey);
}
public string DecryptPwd(string text)
{
return Decrypt(text, PwdKey);
}
public string EncryptHashTkn(string text)
{
return Encrypt(text, HashKey);
}
public string DecryptHashTkn(string text)
{
return Decrypt(text, HashKey);
}
private static string Encrypt(string text, string hash)
{
try
{
byte[] bytesHash = UTF8Encoding.UTF8.GetBytes(hash);
byte[] bytes = UTF8Encoding.UTF8.GetBytes(text);
MD5 md5 = MD5.Create();
TripleDES trpl = TripleDES.Create();
trpl.Key = md5.ComputeHash(bytesHash);
trpl.Mode = CipherMode.ECB;
ICryptoTransform transformer = trpl.CreateEncryptor();
byte[] res = transformer.TransformFinalBlock(bytes, 0, bytes.Length);
return Convert.ToBase64String(res);
}
catch (Exception ex)
{
return ex.Message;
}
}
private static string Decrypt(string encText, string hash)
{
try
{
//string hash = Environment.GetEnvironmentVariable("MySecretKey")!;
byte[] bytesHash = UTF8Encoding.UTF8.GetBytes(hash);
byte[] bytes = Convert.FromBase64String(encText);
MD5 md5 = MD5.Create();
TripleDES trpl = TripleDES.Create();
trpl.Key = md5.ComputeHash(bytesHash);
trpl.Mode = CipherMode.ECB;
ICryptoTransform transformer = trpl.CreateDecryptor();
byte[] res = transformer.TransformFinalBlock(bytes, 0, bytes.Length);
return UTF8Encoding.UTF8.GetString(res);
}
catch (Exception ex)
{
return ex.Message;
}
}
public static string Cypher(string value)
{
string encryptedText = "";
for (int i = 0; i < value.Length; i++)
{
int txtUser = (int)value[i];
int encryption = txtUser + _SEMILLA;
encryptedText += Char.ConvertFromUtf32(encryption);
}
return Base64Encode(encryptedText);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
}
}

View File

@ -0,0 +1,13 @@
<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

@ -0,0 +1,31 @@
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
}
}

18
AuthWebApi/Program.cs Normal file
View File

@ -0,0 +1,18 @@
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

@ -0,0 +1,30 @@
{
"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

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

View File

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

48
BackApiGateway.sln Normal file
View File

@ -0,0 +1,48 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32328.378
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApiGateway", "ApiGateway", "{9F5D8D1C-CF99-4BDD-8497-0123656B8A48}"
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
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{AC631810-7FAF-4C9A-A35D-3EC538A49810}.Debug|Any CPU.ActiveCfg = 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.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
{76522272-9D28-4168-8296-AFC933D22650}.Release|Any CPU.Build.0 = Release|Any CPU
{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{AC631810-7FAF-4C9A-A35D-3EC538A49810} = {9F5D8D1C-CF99-4BDD-8497-0123656B8A48}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EC576D5A-ADE3-40CC-BF55-7E52E6F18AC4}
EndGlobalSection
EndGlobal

View File

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

View File

@ -0,0 +1,97 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Security;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Web;
namespace IntegradorBE.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private static readonly Encripter _encript = new();
[HttpPost("Login")]
public IActionResult Login()
{
try
{
var ip = "";
if (HttpContext?.Connection?.RemoteIpAddress != null)
ip = HttpContext.Connection.RemoteIpAddress.ToString();
if (String.IsNullOrWhiteSpace(ip))
ip = HttpContext?.Request.Headers["REMOTE_ADDR"];
if (!_encript.IsValid) return BadRequest("Lectura inválida");
if (String.IsNullOrWhiteSpace(ip)) return Unauthorized("Acceso no autorizado.");
//Security key debe ser un environment variable seguro
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Encripter.HashKey));
var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
ClaimsIdentity claims = new ClaimsIdentity(new List<Claim>
{
new Claim("IP", ip),
new Claim("permisos", _encript.EncryptHashTkn("externo") + "::-1")
});
var securityTokenDescriptor = new SecurityTokenDescriptor
{
Subject = claims,
Expires = DateTime.Now.AddDays(20),
SigningCredentials = signingCredentials
};
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
var token = jwtSecurityTokenHandler.WriteToken(securityToken);
return Ok(new {
token = Encripter.Cypher(token)
});
} catch (Exception e)
{
return BadRequest(e.Message);
}
}
[HttpGet("Encriptar")]
public IActionResult Encriptar(string text, int tipo)
{
if (!_encript.IsValid) return BadRequest("Lectura inválida");
if (tipo == 0) return Ok(_encript.EncryptPwd(text));
return Ok(_encript.EncryptHashTkn(text));
}
[HttpGet("Desencriptar")]
public IActionResult Desencriptar(string text, int tipo)
{
if (!_encript.IsValid) return BadRequest("Lectura inválida");
if (tipo == 0) return Ok(_encript.DecryptPwd(text));
return Ok(_encript.DecryptHashTkn(text));
}
}
public class LoginModel
{
public string? TX_CORREO_USUMS { get; set; }
public string? TX_PASSWORD_USUMS { get; set; }
}
}

View File

@ -0,0 +1,72 @@
using Microsoft.AspNetCore.Mvc;
namespace IntegradorBE.Controllers
{
[ApiController]
[Route("[controller]")]
public class UPCController : ControllerBase
{
[HttpGet]
public IActionResult UPC(string TX_DOC_AFIL)
{
try{
if (TX_DOC_AFIL == null) return Conflict("Introduzca un valor para consultar");
UPCModel[] upc = new UPCModel[5];
upc[0] = new UPCModel
{
TX_DOC_AFIL = "7818322",
NU_VALORUPC_UPC = 300000,
};
upc[1] = new UPCModel
{
TX_DOC_AFIL = "234wert",
NU_VALORUPC_UPC = 20000,
};
upc[2] = new UPCModel
{
TX_DOC_AFIL = "900578105",
NU_VALORUPC_UPC = 10000,
};
upc[3] = new UPCModel
{
TX_DOC_AFIL = "1452145",
NU_VALORUPC_UPC = 50000,
};
upc[4] = new UPCModel
{
TX_DOC_AFIL = "127647831",
NU_VALORUPC_UPC = 70000,
};
var existe = upc.FirstOrDefault(x => x.TX_DOC_AFIL == TX_DOC_AFIL)?.NU_VALORUPC_UPC;
if (existe != null)
{
return Ok(existe);
}
return Ok("El documento no existe");
}
catch(Exception ex)
{
return BadRequest(ex);
}
}
}
public class UPCModel
{
public string? TX_DOC_AFIL { get; set; }
public decimal? NU_VALORUPC_UPC { get; set; }
}
}

View File

@ -0,0 +1,18 @@
<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" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.25.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Auth\Auth.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32519.379
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegradorBE", "IntegradorBE.csproj", "{494E091E-7088-418E-A823-D313FC51D4CE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Auth", "..\Auth\Auth.csproj", "{D7302A1B-4C0E-4FF4-83FC-4DB768976A2A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{494E091E-7088-418E-A823-D313FC51D4CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{494E091E-7088-418E-A823-D313FC51D4CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{494E091E-7088-418E-A823-D313FC51D4CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{494E091E-7088-418E-A823-D313FC51D4CE}.Release|Any CPU.Build.0 = Release|Any CPU
{D7302A1B-4C0E-4FF4-83FC-4DB768976A2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D7302A1B-4C0E-4FF4-83FC-4DB768976A2A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D7302A1B-4C0E-4FF4-83FC-4DB768976A2A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7302A1B-4C0E-4FF4-83FC-4DB768976A2A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9C57CBEF-459D-496E-986C-9242C9201016}
EndGlobalSection
EndGlobal

42
IntegradorBE/Program.cs Normal file
View File

@ -0,0 +1,42 @@
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();
// Enable Cors
builder.Services.AddCors(options => {
options.AddPolicy(name: "widthoutCors",
builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors("widthoutCors");
if (app.Environment.IsDevelopment())
{
Environment.SetEnvironmentVariable("Mode", "Dev");
}
else
{
Environment.SetEnvironmentVariable("Mode", "Prod");
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,32 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:18821",
"sslPort": 44327
}
},
"profiles": {
"IntegradorBE": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7082;http://localhost:5082",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"MySecretKey": "_ll@v3Segur1d4d!123"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,40 @@
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

@ -0,0 +1,16 @@
<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

@ -0,0 +1,81 @@
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

@ -0,0 +1,14 @@
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

@ -0,0 +1,15 @@
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

@ -0,0 +1,17 @@
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

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

View File

@ -0,0 +1,45 @@
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;
}
}
}

25
TestApi1/Program.cs Normal file
View File

@ -0,0 +1,25 @@
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

@ -0,0 +1,31 @@
{
"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
}
}
}

13
TestApi1/TestApi1.csproj Normal file
View File

@ -0,0 +1,13 @@
<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

@ -0,0 +1,13 @@
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

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

View File

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

View File

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

View File

@ -0,0 +1,28 @@
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

@ -0,0 +1,45 @@
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;
}
}
}

28
TestApi2/Program.cs Normal file
View File

@ -0,0 +1,28 @@
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

@ -0,0 +1,31 @@
{
"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
}
}
}

17
TestApi2/TestApi2.csproj Normal file
View File

@ -0,0 +1,17 @@
<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

@ -0,0 +1,13 @@
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

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

View File

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

Binary file not shown.

0
ocelot.json Normal file
View File