ServiceStack中是否有与ValidateAntiForgeryToken等效的内容?

时间:2013-08-06 19:52:09

标签: c# servicestack

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

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分: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;
        }
    }