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 { //======================================================================= /// /// Extend IApplicationBuilder class to use the anit-forgery token validation middleware. /// public static class ApplicationBuilderExtensions { public static IApplicationBuilder UseAntiforgeryTokens(this IApplicationBuilder app) { return app.UseMiddleware(); } } //======================================================================= /// /// Ensure relevant actions validate the anti-forgery token, eg. post requests. /// 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) { // Log action. //String rawTarget = context.Features.Get().RawTarget; HashSet pathsToIgnore = new HashSet(StringComparer.InvariantCultureIgnoreCase) { "/Security/Ajax/ScorePassword", "/Security/Ajax/KeepLoggedIn" }; if (SbmSystem.DebugMode && !context.Request.Method.EqualsCI("GET") && !pathsToIgnore.Contains($"{context.Request.Path}")) SaLogger.Debug($"{SysUtil.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($"{SysUtil.Fn} " + ExceptionUtil.GetLogMessage(exc)); throw; } } } //======================================================================= }