marco.pms.api/Marco.Pms.Services/Middleware/EncryptionMiddleware.cs

79 lines
2.8 KiB
C#

using Marco.Pms.Services.Service.ServiceInterfaces;
using System.Text;
public class EncryptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IAesEncryption _encryptionService;
// Define the paths you want to SKIP encryption for
private readonly List<string> _ignoredPaths = new List<string>
{
"/hubs/marco",
"/swagger" // Always exclude swagger UI
};
public EncryptionMiddleware(RequestDelegate next, IAesEncryption encryptionService)
{
_next = next;
_encryptionService = encryptionService;
}
public async Task InvokeAsync(HttpContext context)
{
// 1. CHECK EXCLUSIONS
// If the path matches an ignored path, skip logic and continue normally
var path = context.Request.Path.Value?.ToLower();
// Condition A: Skip if path is in the ignored list
bool isIgnoredPath = _ignoredPaths.Any(p => path != null && path.StartsWith(p.ToLower()));
//bool isIgnoredPath = (path != null && !path.StartsWith("/api/expense/list"));
// Condition B: User requested to ONLY encrypt 'GET' methods.
// If the method is POST, PUT, DELETE, etc., we skip encryption.
//bool isNotGetMethod = !HttpMethods.IsGet(context.Request.Method);
//if (isIgnoredPath || isNotGetMethod)
if (isIgnoredPath)
{
await _next(context);
return;
}
// 2. PREPARE TO CAPTURE RESPONSE
// We hold onto the original stream to write back to it later
var originalBodyStream = context.Response.Body;
using (var memoryStream = new MemoryStream())
{
// Point the response body to our memory stream
context.Response.Body = memoryStream;
// 3. EXECUTE THE PIPELINE (The Controller runs here)
await _next(context);
// 4. ENCRYPT RESPONSE
// Reset pointer to read the stream
memoryStream.Seek(0, SeekOrigin.Begin);
// Read the plain JSON
var plainBodyText = await new StreamReader(memoryStream).ReadToEndAsync();
// Encrypt it
var encryptedBodyBase64 = _encryptionService.EncryptResponse(plainBodyText);
var encryptedBytes = Encoding.UTF8.GetBytes(encryptedBodyBase64);
// 5. WRITE TO ORIGINAL STREAM
// Switch back to the original stream
context.Response.Body = originalBodyStream;
// Important: Update Content-Length because the size changed
context.Response.ContentLength = encryptedBytes.Length;
// Optional: Change Content-Type to text/plain since it's now a Base64 string, not JSON
// context.Response.ContentType = "text/plain";
await context.Response.Body.WriteAsync(encryptedBytes, 0, encryptedBytes.Length);
}
}
}