How to change the name of the cookie that the token creates in the forms?

0

I have a form where I occupy @Html.AntiForgeryToken() which creates a cookie of name __RequestVerificationToken which I want to hide. For this I thought about changing the name of that cookie to another one so as not to make it so evident that it is from ASP.NET or that it is the authorization token of forms.

Can someone help me with this?

    
asked by vcasas 13.06.2018 в 23:52
source

1 answer

5

We go in parts, first to the file: global.asax.cs

public void Application_Start()
{

....
AntiForgeryConfig.CookieName = "__ElNombreQueDeseesComoToken";
...

}

To avoid problems, problems, hairs or whatever you want to call it, we are going to create an Html Helper

public static MvcHtmlString myAntiForgeryToken(this HtmlHelper helper)
{
    return new MvcHtmlString(AntiForgery.GetHtml().ToString().Replace("__RequestVerificationToken", AntiForgeryConfig.CookieName));
}

To avoid confusion, we will create a new attribute , in such a way that we can "decorate" the controllers to make them safe, by the way, they will use the new name of the cookie.

using System;
using System.Web.Helpers;
using System.Web.Mvc;

namespace myNamespace
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class myValidateAntiForgeryTokenAttribute :
    FilterAttribute,
    IAuthorizationFilter
    {

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            try
            {
                var httpContext = filterContext.HttpContext;
                var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
                AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Form[AntiForgeryConfig.CookieName]);
            }
            catch
            {
                throw;

            }
        }

    }
}

To close with a flourish, to each controller where you have used the great and illustrious [ValidateAntiForgeryToken] you must change it to the new attribute [myValidateAntiForgeryToken] and in each view where you have used @Html.AntiForgeryToken() you replace it with a @Html.myAntiForgeryToken()

    
answered by 14.06.2018 / 00:31
source