Added encryption middleware for all APIs
This commit is contained in:
parent
bd4bd90e7b
commit
4320f92964
79
Marco.Pms.Services/Middleware/EncryptionMiddleware.cs
Normal file
79
Marco.Pms.Services/Middleware/EncryptionMiddleware.cs
Normal file
@ -0,0 +1,79 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -188,7 +188,6 @@ builder.Services.AddScoped<IMasterService, MasterService>();
|
||||
builder.Services.AddScoped<IDirectoryService, DirectoryService>();
|
||||
builder.Services.AddScoped<IFirebaseService, FirebaseService>();
|
||||
builder.Services.AddScoped<IRazorpayService, RazorpayService>();
|
||||
builder.Services.AddScoped<IAesEncryption, AesEncryption>();
|
||||
builder.Services.AddScoped<IOrganizationService, OrganizationService>();
|
||||
builder.Services.AddScoped<ITenantService, TenantService>();
|
||||
builder.Services.AddScoped<IServiceProject, ServiceProjectService>();
|
||||
@ -215,6 +214,7 @@ builder.Services.AddScoped<SidebarMenuHelper>();
|
||||
|
||||
// Singleton services (one instance for the app's lifetime)
|
||||
builder.Services.AddSingleton<ILoggingService, LoggingService>();
|
||||
builder.Services.AddSingleton<IAesEncryption, AesEncryption>();
|
||||
|
||||
string path = Path.Combine(builder.Environment.ContentRootPath, "FireBase", "service-account.json");
|
||||
|
||||
@ -244,6 +244,7 @@ var app = builder.Build();
|
||||
app.UseMiddleware<ExceptionHandlingMiddleware>();
|
||||
app.UseMiddleware<TenantMiddleware>();
|
||||
app.UseMiddleware<LoggingMiddleware>();
|
||||
app.UseMiddleware<EncryptionMiddleware>();
|
||||
#endregion
|
||||
|
||||
#region Development Environment Configuration
|
||||
|
||||
@ -32,5 +32,35 @@ namespace Marco.Pms.Services.Service
|
||||
|
||||
return Encoding.UTF8.GetString(plaintext);
|
||||
}
|
||||
|
||||
public string EncryptResponse(string plainText)
|
||||
{
|
||||
var key = Convert.FromBase64String("h9J4kL2mN5pQ8rS1tV3wX6yZ0aB7cD9eF1gH3jK5mN6=");
|
||||
if (string.IsNullOrEmpty(plainText)) return plainText;
|
||||
|
||||
var plainBytes = Encoding.UTF8.GetBytes(plainText);
|
||||
|
||||
// 1. Generate Nonce (12 bytes)
|
||||
var nonce = new byte[12];
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
|
||||
// 2. Prepare Buffers
|
||||
var tag = new byte[16];
|
||||
var ciphertext = new byte[plainBytes.Length];
|
||||
|
||||
// 3. Encrypt
|
||||
using (var aesGcm = new AesGcm(key, 16))
|
||||
{
|
||||
aesGcm.Encrypt(nonce, plainBytes, ciphertext, tag);
|
||||
}
|
||||
|
||||
// 4. Combine: [Nonce] + [Ciphertext] + [Tag]
|
||||
var combined = new byte[nonce.Length + ciphertext.Length + tag.Length];
|
||||
Buffer.BlockCopy(nonce, 0, combined, 0, nonce.Length);
|
||||
Buffer.BlockCopy(ciphertext, 0, combined, nonce.Length, ciphertext.Length);
|
||||
Buffer.BlockCopy(tag, 0, combined, nonce.Length + ciphertext.Length, tag.Length);
|
||||
|
||||
return Convert.ToBase64String(combined);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,5 +4,6 @@
|
||||
{
|
||||
(byte[] ciphertext, byte[] nonce, byte[] tag) Encrypt(string plaintext, byte[] key);
|
||||
string Decrypt(byte[] ciphertext, byte[] nonce, byte[] tag, byte[] key);
|
||||
string EncryptResponse(string plainText);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user