Example #1
0
        private string GetAntiForgeryTokenAndSetCookie(string salt, string domain, string path)
        {
            string cookieName = AntiForgeryData.GetAntiForgeryTokenName(ViewContext.HttpContext.Request.ApplicationPath);

            AntiForgeryData cookieToken;
            HttpCookie      cookie = ViewContext.HttpContext.Request.Cookies[cookieName];

            if (cookie != null)
            {
                cookieToken = Serializer.Deserialize(cookie.Value);
            }
            else
            {
                cookieToken = AntiForgeryData.NewToken();
                string cookieValue = Serializer.Serialize(cookieToken);

                HttpCookie newCookie = new HttpCookie(cookieName, cookieValue)
                {
                    HttpOnly = true, Domain = domain
                };
                if (!String.IsNullOrEmpty(path))
                {
                    newCookie.Path = path;
                }
                ViewContext.HttpContext.Response.Cookies.Set(newCookie);
            }

            AntiForgeryData formToken = new AntiForgeryData(cookieToken)
            {
                CreationDate = DateTime.Now,
                Salt         = salt
            };
            string formValue = Serializer.Serialize(formToken);

            return(formValue);
        }