using Microsoft.Net.Http.Headers; using Ocelot.Middleware; using System.Net; using System.Security.Claims; namespace ApiGateway.Middleware { public class OcelotJwtMiddleware : OcelotPipelineConfiguration { private static readonly string RoleSeparator = ","; /* Nota: No tengo ni idea de por qué este método es necesario, pero hace que funcione... */ public OcelotJwtMiddleware() { PreAuthorizationMiddleware = async (ctx, next) => { await ProcessRequest(ctx, next); }; } public async Task ProcessRequest(HttpContext context, Func 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()); 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 { 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); } } }