70 lines
2.0 KiB
C#
70 lines
2.0 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";
|
|
|
|
// Log action.
|
|
//String rawTarget = context.Features.Get<IHttpRequestFeature>().RawTarget;
|
|
if (SbmSystem.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;
|
|
}
|
|
}
|
|
}
|
|
|
|
//=======================================================================
|
|
}
|