mirror of
https://github.com/techgarage-ir/MTWireGuard.git
synced 2025-08-28 22:08:08 +02:00
Add project files.
This commit is contained in:
commit
b2325a46ef
1351 changed files with 48136 additions and 0 deletions
64
Middlewares/AntiForgeryMiddleware.cs
Normal file
64
Middlewares/AntiForgeryMiddleware.cs
Normal file
|
@ -0,0 +1,64 @@
|
|||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using MTWireGuard.Pages;
|
||||
using MTWireGuard.Repositories;
|
||||
using Newtonsoft.Json;
|
||||
using Razor.Templating.Core;
|
||||
using System.Globalization;
|
||||
|
||||
namespace MTWireGuard.Middlewares
|
||||
{
|
||||
public class AntiForgeryMiddleware : IMiddleware
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
|
||||
{
|
||||
if (context.Request.Path.Value == "/Login")
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
var antiForgeryService = context.RequestServices.GetRequiredService<IAntiforgery>();
|
||||
var isGetRequest = string.Equals("GET", context.Request.Method, StringComparison.OrdinalIgnoreCase);
|
||||
if (!isGetRequest)
|
||||
{
|
||||
await antiForgeryService.ValidateRequestAsync(context);
|
||||
}
|
||||
}
|
||||
catch (AntiforgeryValidationException ex)
|
||||
{
|
||||
string response = string.Empty;
|
||||
ErrorModel errorModel = new();
|
||||
Dictionary<string, object> ViewBag = new()
|
||||
{
|
||||
["Title"] = "XSRF token validation failed!",
|
||||
["Message"] = ex.Message
|
||||
};
|
||||
if (context.Request.Path.Value == "/Login")
|
||||
response = await RazorTemplateEngine.RenderAsync("/Pages/Error.cshtml", errorModel, ViewBag);
|
||||
else
|
||||
{
|
||||
var result = new Dictionary<string, string>()
|
||||
{
|
||||
{"background", "danger"},
|
||||
{"title", ViewBag["Title"].ToString()},
|
||||
{"body", ViewBag["Message"].ToString()},
|
||||
};
|
||||
response = JsonConvert.SerializeObject(result);
|
||||
}
|
||||
context.Response.StatusCode = 200;
|
||||
await context.Response.WriteAsync(response);
|
||||
return;
|
||||
}
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
|
||||
public static class AntiForgeryMiddlewareExtensions
|
||||
{
|
||||
public static IApplicationBuilder UseAntiForgery(this IApplicationBuilder builder)
|
||||
{
|
||||
return builder.UseMiddleware<AntiForgeryMiddleware>();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue