Files
BusinessMgr-2019/SaBusMgrCoreWeb/Web/Middleware/ValidateAntiForgeryTokenMiddleware.cs

71 lines
2.3 KiB
C#

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Sarand.BusinessMgr.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Utils;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Sarand.BusinessMgr.Net.Core.Web.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"; // SysUtil.Fn not useable.
// Log action.
//String rawTarget = context.Features.Get<IHttpRequestFeature>().RawTarget;
HashSet<String> pathsToIgnore = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "/Security/Ajax/ScorePassword", "/Security/Ajax/KeepLoggedIn" };
if (SbmSystem.DebugMode && !context.Request.Method.EqualsCI("GET") && !pathsToIgnore.Contains($"{context.Request.Path}"))
SaLogger.Debug($"{fn} Action: '{Regex.Replace($"{context.Request.Path}", "^/", "")}'. 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;
}
}
}
//=======================================================================
}