Apigateway/ApiGateway/OcelotJwtMiddleware.cs
2022-11-02 11:31:23 -05:00

111 lines
3.8 KiB
C#

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