Files
Saxonite/SaxoniteCoreWeb/Base/Middleware/ValidateAntiForgeryTokenMiddleware.cs
T
2021-05-11 19:38:43 +01:00

72 lines
2.1 KiB
C#

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Utils;
using Saxonite.Net.Standard.Base.App;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Saxonite.Net.Core.Web.Base.Middleware
{
//=======================================================================
/// <summary>
/// Extend IApplicationBuilder class to use the anit-forgery token validation middleware.
/// </summary>
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseAntiforgeryTokens(this IApplicationBuilder app)
{
return app.UseMiddleware<ValidateAntiForgeryTokenMiddleware>();
}
}
//=======================================================================
/// <summary>
/// Ensure relevant actions validate the anti-forgery token, eg. post requests.
/// </summary>
public class ValidateAntiForgeryTokenMiddleware
{
private readonly RequestDelegate _next;
private readonly IAntiforgery _antiforgery;
public ValidateAntiForgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiforgery)
{
_next = next;
_antiforgery = antiforgery;
}
public async Task Invoke(HttpContext context)
{
String fn = GetType().Name + ".Invoke";
// Log action.
//String rawTarget = context.Features.Get<IHttpRequestFeature>().RawTarget;
if (SaxSystem.DebugMode) SaLogger.Debug(fn + " Action: '" + Regex.Replace(context.Request.Path.ToString(), "^/", "") + "'. Method: " + context.Request.Method);
// Intercept POST requests and apply anti-forgery test.
if (HttpMethods.IsPost(context.Request.Method))
{
await _antiforgery.ValidateRequestAsync(context);
}
try
{
await _next(context);
}
catch (Exception exc)
{
SaLogger.Warn(fn + " " + ExceptionUtil.GetLogMessage(exc));
throw exc;
}
}
}
//=======================================================================
}