Skip to content

Commit

Permalink
REFACTOR: Middleware refacotr to use IMiddleware interface.
Browse files Browse the repository at this point in the history
  • Loading branch information
CesarD committed Mar 1, 2024
1 parent 19b04a4 commit cfba276
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Monaco.Template.Backend.Common.Api.Attributes;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Monaco.Template.Backend.Common.Api.Middleware;

Expand All @@ -11,21 +11,14 @@ namespace Monaco.Template.Backend.Common.Api.Middleware;
/// This middleware is useful for cases where there's an API Gateway in front of the API but some endpoints still need to validate some user's claims as part of the business rules, so this makes that available.
/// It's assumed that the JWT token passed has already been validated by the eventual API Gateway on top of the API.
/// </summary>
public class JwtClaimsMapperMiddleware
public class JwtClaimsMapperMiddleware : IMiddleware
{
private readonly RequestDelegate _next;

private const string SchemeStr = $"{JwtBearerDefaults.AuthenticationScheme} ";
private const string ScopeClaimType = "scope";
private const string NameClaimType = "name";
private const string RoleClaimType = "role";

public JwtClaimsMapperMiddleware(RequestDelegate next)
{
_next = next;
}

public Task InvokeAsync(HttpContext context)

public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (context.GetEndpoint()?.Metadata.Any(x => x is JwtMapClaimsAttribute) ?? false)
{
Expand All @@ -47,6 +40,6 @@ public Task InvokeAsync(HttpContext context)
}
}

return _next(context);
return next(context);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,12 @@

namespace Monaco.Template.Backend.Common.Api.Middleware;

public class SerilogContextEnricherMiddleware
public class SerilogContextEnricherMiddleware : IMiddleware
{
private readonly RequestDelegate _next;

private const string UserIdType = "sub";
private const string UserNameType = "preferred_username";

public SerilogContextEnricherMiddleware(RequestDelegate next)
{
_next = next;
}

public Task Invoke(HttpContext context)

public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var user = context.User;
if (user.HasClaim(x => x.Type == UserIdType))
Expand All @@ -25,6 +18,6 @@ public Task Invoke(HttpContext context)
if (user.HasClaim(x => x.Type == UserNameType))
LogContext.PushProperty("userName", context.User.FindFirstValue(UserNameType));

return _next(context);
return next(context);
}
}

0 comments on commit cfba276

Please sign in to comment.