I want to implement antiforgery token in sitecore forms without razor view how can I achieve this
2 Answers
To implement antifrogery token in sitecore forms without razor view
Create a custom renderForm pipeline processor to add anti-forgery token and injects the anti-forgery token into the form markup during rendering
namespace MyProject.Forms.Pipelines { public class AddAntiforgeryToken : RenderFormProcessor { public override void Process(RenderFormEventArgs args) { var context = HttpContext.Current; string cookieToken, formToken; AntiForgery.GetTokens(null, out cookieToken, out formToken); string tokenValue = cookieToken + ":" + formToken; var tokenInput = $"<input type='hidden' name='__RequestVerificationToken' value='{tokenValue}' />"; args.Result += tokenInput; } } } Create a patch file in /App_Config/Include/Project/zzz called something like Project.Forms.AntiForgery.config
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <renderForm> <processor type="MyProject.Forms.Pipelines.AddAntiforgeryToken, MyProject" patch:after="*[@type='Sitecore.ExperienceForms.Mvc.Pipelines.RenderForm.RenderForm, Sitecore.ExperienceForms.Mvc']" /> </renderForm> </pipelines> </sitecore> </configuration> Create a submit action processor as the Anti-Forgery Token Validator
namespace MyProject.Forms.SubmitActions { public class ValidateAntiForgeryToken : SubmitActionBase<string> { public ValidateAntiForgeryToken(ISubmitActionData data) : base(data) {} protected override bool Execute(string data, FormSubmitContext context) { try { AntiForgery.Validate(); return true; } catch (HttpAntiForgeryException ex) { return false; } } } } Register the class as Sitecore Forms Submit Action in Sitecore config sitecore.experienceforms.submitActions:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <experienceforms> <submitActions> <submitAction name="Validate Anti-Forgery Token"> <patch:attribute name="type">MyProject.Forms.SubmitActions.ValidateAntiForgeryToken, MyProject</patch:attribute> <patch:attribute name="editor">Sitecore.ExperienceForms.UI.Dialogs.SubmitActions.SingleLineText, Sitecore.ExperienceForms</patch:attribute> </submitAction> </submitActions> </experienceforms> </sitecore> </configuration> After these steps Validate Anti-Forgery Token action will be available in the Forms Designer under Submit Actions list.
Hope this helps!
To implement antiforgery tokens in Sitecore Forms without Razor:
- create an API using
IAntiforgeryto return the token - use JavaScript to inject it into the form as a hidden input
__RequestVerificationToken - and create a custom submit action that calls
_antiforgery.ValidateRequestAsync(HttpContext)to validate the token on form submission.
Hope this helps!!!