Example #1
0
        //Return something better than tuple?
        private static Tuple <string, string> GetTokens(string oldCookieToken = null)
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(oldCookieToken, out cookieToken, out formToken);
            return(Tuple.Create(cookieToken, formToken));
        }
Example #2
0
        /// <summary>
        /// Generates an anti-forgery token to be sent with a form submission using the name
        /// "__RequestVerificationToken".
        /// </summary>
        /// <returns>
        /// The token.
        /// </returns>
        /// <remarks>
        /// This will also read in and set the appropriate cookie tokens for the current request/response.
        /// </remarks>
        public static string GenerateAntiForgeryToken()
        {
            // Variables.
            var context        = HttpContext.Current;
            var request        = context.Request;
            var response       = context.Response;
            var cookie         = request.Cookies[AntiForgeryConfig.CookieName];
            var oldCookieToken = cookie?.Value;
            var cookieToken    = default(string);
            var formToken      = default(string);


            // Get tokens (a cookie token and a form token).
            AntiForgery.GetTokens(oldCookieToken, out cookieToken, out formToken);


            // If a new cookie token was generated, set it in the response.
            if (!string.IsNullOrEmpty(cookieToken))
            {
                cookie       = cookie ?? new HttpCookie(AntiForgeryConfig.CookieName);
                cookie.Value = cookieToken;
                response.Cookies.Add(cookie);
            }


            // Return the form token.
            return(formToken);
        }
Example #3
0
        public HttpResponseMessage GetAntiForgeryToken()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            HttpCookie          cookie   = HttpContext.Current.Request.Cookies[AppConstants.XsrfCookie];
            string oldCookieToken        = cookie == null ? "" : cookie.Value;
            string cookieToken;
            string formToken;

            AntiForgery.GetTokens(oldCookieToken, out cookieToken, out formToken);

            var content = new { FormToken = formToken, CookieToken = cookieToken };

            response.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

            if (!string.IsNullOrEmpty(cookieToken))
            {
                CookieHeaderValue cookieData = new CookieHeaderValue(AppConstants.XsrfCookie, cookieToken);
                cookieData.Expires = DateTimeOffset.Now.AddMinutes(10);
                cookieData.Domain  = Request.RequestUri.Host;
                cookieData.Path    = "/";
                response.Headers.AddCookies(new CookieHeaderValue[] { cookieData });
            }

            return(response);
        }
Example #4
0
        public static string AntiForgeryToken(this FormModel model)
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(string.Format("{0}:{1}", cookieToken, formToken));
        }
        private static string GetAntiForgeryToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(String.Concat(cookieToken, ":", formToken));
        }
Example #6
0
        public string GetToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(cookieToken + TOKEN_DELIMITER + formToken);
        }
        //public static

        public static string CsrfTokenHeaderValue(this HtmlHelper htmlHelper)
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(cookieToken + ":" + formToken);
        }
Example #8
0
        public MvcHtmlString GetAntiForgeryToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(new MvcHtmlString(string.Format("{0}:{1}", cookieToken, formToken)));
        }
        /// <inheritdoc/>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext is null)
            {
                throw new ArgumentNullException(nameof(actionExecutedContext));
            }

            var cookieName            = CookieName ?? WebApiAntiForgeryConfig.TokenCookieName;
            var cookiePath            = CookiePath ?? WebApiAntiForgeryConfig.TokenCookiePath;
            var requireSsl            = AntiForgeryConfig.RequireSsl;
            var antiForgeryCookieName = AntiForgeryConfig.CookieName;

            // Thread safety? Async?
            var request  = HttpContext.Current.Request;
            var response = HttpContext.Current.Response;

            // TODO: I'm not sure we need to check both.
            var oldCookieToken = SafeGet(response.Cookies, antiForgeryCookieName)?.Value ?? SafeGet(request.Cookies, antiForgeryCookieName)?.Value;

            // TODO: Should we only set the token cookie if there isn't already one, or is it better to change it every time?
            AntiForgery.GetTokens(oldCookieToken, out var newCookieToken, out var formToken);

            if (!string.IsNullOrEmpty(newCookieToken))
            {
                response.SetCookie(new HttpCookie(antiForgeryCookieName, newCookieToken)
                {
                    HttpOnly = true, Secure = requireSsl
                });                                                                                                                 // TODO: Secure = request.IsSecureConnection?
            }

            response.SetCookie(new HttpCookie(cookieName, formToken)
            {
                HttpOnly = false, Secure = requireSsl, Path = cookiePath
            });
        }
        public HttpResponseMessage GetAntiForgeryToken()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            HttpCookie cookie = HttpContext.Current.Request.Cookies["xsrf-token"];

            string cookieToken;
            string formToken;

            AntiForgery.GetTokens(cookie == null ? "" : cookie.Value, out cookieToken, out formToken);

            AntiForgeryTokenModel content = new AntiForgeryTokenModel
            {
                AntiForgeryToken = formToken
            };

            response.Content = new StringContent(
                JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

            if (!string.IsNullOrEmpty(cookieToken))
            {
                response.Headers.AddCookies(new[]
                {
                    new CookieHeaderValue("xsrf-token", cookieToken)
                    {
                        Expires = DateTimeOffset.Now.AddMinutes(10),
                        Path    = "/"
                    }
                });
            }

            return(response);
        }
Example #11
0
        // [NoCache]
        public JsonResult GetAntiForgeryToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(Json(new { cookieToken = cookieToken, formToken = formToken }, JsonRequestBehavior.AllowGet));
        }
Example #12
0
        public static string TokenHeaderValue()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(cookieToken + ":" + formToken);
        }
Example #13
0
        public string GetToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(cookieToken + ":" + formToken);
        }
Example #14
0
        private static readonly Lazy <byte[]> KeyD = new Lazy <byte[]>(() => Convert.FromBase64String(Config.NodeBB.KeyD)); // decrypt

        public static string GenerateAuthUrl(HttpContextBase context)
        {
            AntiForgery.GetTokens(context.Request.Cookies[AntiForgeryConfig.CookieName]?.Value, out var newCookieToken, out var formToken);
            if (newCookieToken != null)
            {
                var cookie = new HttpCookie(AntiForgeryConfig.CookieName, newCookieToken)
                {
                    HttpOnly = true
                };

                // Only override to true, never to false.
                if (AntiForgeryConfig.RequireSsl)
                {
                    cookie.Secure = true;
                }

                context.Response.Cookies.Set(cookie);
            }

            var uri = "https://" + Config.NodeBB.Host + "/api/tdwtf-front-page-auth?state=" + Uri.EscapeDataString(Encrypt(formToken));

            if (!string.Equals(Config.Wtf.Host, "thedailywtf.com", StringComparison.OrdinalIgnoreCase))
            {
                uri += "&target=" + Uri.EscapeDataString(Encrypt("https://" + Config.Wtf.Host + "/login/nodebb"));
            }
            return(uri);
        }
        public static MvcHtmlString CustomAntiForgeryToken(this HtmlHelper htmlHelper)
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            var responseCookie = new HttpCookie("__AJAXAntiXsrfToken")
            {
                HttpOnly = true,
                Value    = cookieToken
            };

            if (FormsAuthentication.RequireSSL && HttpContext.Current.Request.IsSecureConnection)
            {
                responseCookie.Secure = true;
            }
            HttpContext.Current.Response.Cookies.Set(responseCookie);

            TagBuilder hidden = new TagBuilder("input");

            hidden.Attributes.Add("type", "hidden");
            hidden.Attributes.Add("name", "__RequestVerificationToken");
            if (formToken != null)
            {
                hidden.Attributes.Add("value", formToken.ToString());
            }
            return(MvcHtmlString.Create(hidden.ToString()));
        }
        private static void WriteForgeryToken(ControllerBase controller)
        {
            string cookieToken, formToken;
            var    context = controller.ControllerContext.HttpContext;

            var oldCookie      = context.Request.Cookies[AntiForgeryConfig.CookieName];
            var oldCookieToken = oldCookie != null ? oldCookie.Value : null;

            AntiForgery.GetTokens(oldCookieToken, out cookieToken, out formToken);
            context.Items[FlushedAntiForgeryTokenKey] = formToken;

            if (AntiForgeryConfig.RequireSsl && !context.Request.IsSecureConnection)
            {
                throw new InvalidOperationException("WebPageResources.AntiForgeryWorker_RequireSSL");
                //TODO: Find string message
            }

            var response = context.Response;

            if (!string.IsNullOrEmpty(cookieToken))
            {
                response.Cookies.Set(new HttpCookie(AntiForgeryConfig.CookieName, cookieToken)
                {
                    HttpOnly = true
                });
            }

            if (!AntiForgeryConfig.SuppressXFrameOptionsHeader)
            {
                // Adding X-Frame-Options header to prevent ClickJacking. See
                // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10
                // for more information.
                response.AddHeader("X-Frame-Options", "SAMEORIGIN");
            }
        }
Example #17
0
        public static string GetCombinedAntiForgeryTokens(string username)
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            HttpContext.Current.Cache[username + "_formToken"] = formToken;
            return(cookieToken + ":" + formToken);
        }
        public string GetAntiForgeryToken()
        {
            string cookieToken, formToken, result;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            result = cookieToken + ":" + formToken;
            return(result);
        }
Example #19
0
        public string GetAntiForgeryTokens()
        {
            string cookieToken = "", formToken = "";

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            HttpContext.Current.Response.Cookies[AntiForgeryConfig.CookieName].Value = cookieToken;
            return(formToken);
        }
Example #20
0
        /// <summary>
        /// Get Token for CSRF
        /// </summary>
        /// <returns></returns>
        public JsonResult GetTocken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            HttpContext.Cache[this.CurrentUser.UserEmail + "_formToken"] = formToken;
            return(this.Json(cookieToken + ":" + formToken, JsonRequestBehavior.AllowGet));
        }
Example #21
0
        private string GenerateXSRFToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);

            return(cookieToken + ":" + formToken);
        }
Example #22
0
        /// <summary>
        /// get csrf token
        /// </summary>
        /// <returns></returns>
        public static string GSIMS_TokenHeaderValue()
        {
            string cookieToken = null;
            string formToken   = null;
            var    dateTime    = DateTime.Now.Ticks.ToString();

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return(string.Format("{0}:{1}:{2}", cookieToken, formToken, CommonHelper.Encrypt(dateTime)));
        }
Example #23
0
        /// <summary>
        /// Returns key-value pair of CSRF token for current visiting state
        /// </summary>
        /// <returns></returns>
        public KeyValuePair <string, string> CSRFToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            var pair = new KeyValuePair <string, string>(Constants.CsrfTokenName, string.Format("{0}:{1}", cookieToken, formToken));

            return(pair);
        }
Example #24
0
        public static string RequestVerificationToken(this HtmlHelper source)
        {
            var cookieToken = string.Empty;
            var formToken   = string.Empty;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);

            return(string.Format("{0}:{1}", cookieToken, formToken));
        }
Example #25
0
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     if (actionExecutedContext.Request.Method != HttpMethod.Get)
     {
         AntiForgery.GetTokens(null, out string cookieToken, out string formToken);
         var token = cookieToken + ":" + formToken;
         actionExecutedContext.Response.Headers.AddCookies("XSRF-TOKEN", token);
     }
     base.OnActionExecuted(actionExecutedContext);
 }
Example #26
0
        public JsonResult GetToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            Auth auth = new Auth();

            auth.token = formToken;
            return(Json(auth, JsonRequestBehavior.AllowGet));
        }
Example #27
0
        public string SetAntiForgeryToken()
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            var cookie = new HttpCookie("XSRF-TOKEN", cookieToken);

            cookie.HttpOnly = true;
            HttpContext.Current.Response.Cookies.Add(cookie);
            return(formToken);
        }
Example #28
0
 public void GetTokens_ThrowsWhenNotCalledInWebContext()
 {
     Assert.Throws <ArgumentException>(
         () =>
     {
         string dummy1,
         dummy2;
         AntiForgery.GetTokens("dummy", out dummy1, out dummy2);
     },
         "An HttpContext is required to perform this operation. Check that this operation is being performed during a web request."
         );
 }
        public Task <IlanIlanlarResponse> IlanEkle([FromBody] EmlakIlanRequest request)
        {
            string cookieToken;
            string formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            var cookieTokenv = cookieToken;
            var formTokenn   = formToken;

            // string[] temp = request["Konular.KategoriID"].Split(',');
            return(_ilanIlanlarEngine.CreateAsync(request));
        }
Example #30
0
        public static IHtmlString AngularAntiForgeryToken(this HtmlHelper helper)
        {
            string cookieToken, formToken;

            AntiForgery.GetTokens(null, out cookieToken, out formToken);

            return(helper.Hidden("__RequestVerificationToken", string.Empty, new
            {
                @id = "__RequestVerificationToken",
                data_ng_model = "antiForgeryToken",
                data_ng_init = "antiForgeryToken='" + cookieToken + ":" + formToken + "'"
            }));
        }