2

我正在 github 中查看 SS 代码,但找不到任何与 ValidateAntiForgeryToken 等效的代码,因为我不想重新发明轮子,我想尽可能多地重用 SS 框架,我认为这是一个解决方案可能是创建一个自定义 RequestFilterAttribute,还有其他想法吗?

4

2 回答 2

3

我最终创建了一个具有与 asp.net mvc 类似功能的 requestFilterAttibute

这是我到目前为止所做的代码:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    public class ValidateHttpAntiForgeryToken : RequestFilterAttribute
    {
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
           try
            {
                if (IsAjaxRequest(req))
                    ValidateRequestHeader(req);
                else
                    AntiForgery.Validate();

            }
            catch (Exception ex)
            {
                res.StatusCode = 403;
                res.StatusDescription = ex.Message;
            }
        }

        private void ValidateRequestHeader(IHttpRequest req)
        {
            var cookie = req.Cookies.FirstOrDefault(c => c.Value.Name.Contains(AntiForgeryConfig.CookieName));
            if (cookie.Value == null)
            {
                throw new HttpAntiForgeryException(String.Format("Missing {0} cookie", AntiForgeryConfig.CookieName));
            }
            IEnumerable<string> xXsrfHeaders = req.Headers.GetValues("__RequestVerificationToken");
            if (xXsrfHeaders == null || !xXsrfHeaders.Any())
                throw new HttpAntiForgeryException("Missing X-XSRF-Token HTTP header");
            AntiForgery.Validate(cookie.Value.Value, xXsrfHeaders.FirstOrDefault());

        }

        private static bool IsAjaxRequest(IHttpRequest request)
        {
            IEnumerable<string> xRequestedWithHeaders = request.Headers.GetValues("X-Requested-With");
            if (xRequestedWithHeaders != null && xRequestedWithHeaders.Any())
            {
                string headerValue = xRequestedWithHeaders.FirstOrDefault();
                if (!String.IsNullOrEmpty(headerValue))
                {
                    return String.Equals(headerValue, "XMLHttpRequest", StringComparison.OrdinalIgnoreCase);
                }
            }
            return false;
        }
    }
于 2013-08-11T06:42:58.287 回答
3

看起来那个轮子已经被发明出来了:

https://github.com/ServiceStack/ServiceStack/tree/master/src/ServiceStack/Html/AntiXsrf

于 2013-08-06T20:17:48.227 回答