Skip to content

Instantly share code, notes, and snippets.

@gerhart92
Last active February 24, 2022 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerhart92/6c1ea49d5c33b1d5637d1160062c458b to your computer and use it in GitHub Desktop.
Save gerhart92/6c1ea49d5c33b1d5637d1160062c458b to your computer and use it in GitHub Desktop.
using System;
using System.Web;
using System.Web.Helpers;
using Sitecore.XA.Foundation.Abstractions;
using Sitecore.XA.Foundation.Scriban.Pipelines.GenerateScribanContext;
using Scriban.Runtime;
namespace Sitecore.Foundation.ScribanExtensions.Scriban
{
public class GetAntiforgeryToken : IGenerateScribanContextProcessor
{
/// <summary>
/// the context
/// </summary>
private readonly IContext context;
private delegate string AntiforgeryTokenUrlDelegate();
public GetAntiforgeryToken(IContext context)
{
this.context = context;
}
public void Process(GenerateScribanContextPipelineArgs args)
{
var antiforgeryTokenUrl = new AntiforgeryTokenUrlDelegate(AntiforgeryToken);
args.GlobalScriptObject.Import("sc_getantiforgerytoken", (Delegate)antiforgeryTokenUrl);
}
public string AntiforgeryToken()
{
string cookieToken, formToken;
string oldToken = null;
// we store a request verification token in cookies also
if (context.HttpContext.Request.Cookies[AntiForgeryConfig.CookieName] != null)
{
oldToken = context.HttpContext.Request.Cookies[AntiForgeryConfig.CookieName].Value;
}
// method to generate request verification tokens
AntiForgery.GetTokens(oldToken, out cookieToken, out formToken);
// if there was a generated new cookie we update the cookie
if (cookieToken != null)
{
// save the generated request verification in cookie, to evade conflict of multiple token generation because of multiple forms in one page
var response = context.HttpContext.Response;
var tokenCookie = new HttpCookie(AntiForgeryConfig.CookieName);
tokenCookie.Value = cookieToken;
// to update the cookie value we need to remove/add the cookie
response.Cookies.Remove(AntiForgeryConfig.CookieName);
response.Cookies.Add(tokenCookie);
}
else
{
cookieToken = oldToken;
}
return cookieToken + ":" + formToken;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment