Last active
February 24, 2022 17:16
-
-
Save gerhart92/6c1ea49d5c33b1d5637d1160062c458b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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