ServiceStack 中是否有任何等效于 ValidateAntiForgeryToken 的东西? [英] Is there any Equivalent to ValidateAntiForgeryToken in ServiceStack?

查看:38
本文介绍了ServiceStack 中是否有任何等效于 ValidateAntiForgeryToken 的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking at SS code in github and I can't to find any equivalent to ValidateAntiForgeryToken because I don't want to reinvent the wheel and I'd like to reuse as much as possible the SS framework, I think that a solution could be to create a custom RequestFilterAttribute, any other ideas?

推荐答案

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

I ended up by creating a requestFilterAttibute with similar capabilities of the asp.net mvc

这是我迄今为止完成的代码:

this is the code I've done so far:

[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;
        }
    }

这篇关于ServiceStack 中是否有任何等效于 ValidateAntiForgeryToken 的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆