【问题标题】:Can I validate HTTP request signature tokens and nonces using Model Binding?我可以使用模型绑定验证 HTTP 请求签名令牌和随机数吗?
【发布时间】:2011-09-18 21:15:15
【问题描述】:

我正在使用 ASP.NET MVC 设置一个端点,可以向该端点发出操作和检索数据的请求(基本上是一个 API)。我正在使用 2-legged OAuth 模型来验证请求是否使用密钥和签名方法以及 nonce 表进行签名以防止劫持。

由于模型绑定在 ASP.NET MVC 中非常方便,我将利用它来处理请求,但我想知道是否可以将签名验证和随机数/时间戳处理直接烘焙到模型绑定器中。这可能吗?这样我就可以在我创建的各种操作上重复使用实现。

【问题讨论】:

    标签: validation asp.net-mvc-3 authorization model-binding nonce


    【解决方案1】:

    我认为你应该可以。试试这个:

    public class FooModelBinder : IModelBinder
        {
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                FooModel fooModel = bindingContext.Model as fooModel;
                if (fooModel != null)
                {
                   // Do your verification stuff in here
                   // Updating any properties of your Model.
                   // Or you could retrieve something else entirely and return it if you like
                   // Let's pretend we just want to verify the model and set some property or other.
                   fooModel.NonceOkay = DoVerification(fooModel);
                   fooModel.NextAction = WorkOutWhereToGoNext(fooModel);
                   // or whatever
                }
                return fooModel;
            }
        }
    

    DoVerification 可以存在于您的 ModelBinder 中,但它最好存在于其他地方。

    然后将其粘贴到 Global.asax 中的 Application_Start 中:

    ModelBinders.Binders.Add(typeof(Foo), new FooModelBinder());
    

    【讨论】:

    • 谢谢。然后,只要我将 Foo 作为操作参数,它就会默认使用该模型绑定器,对吗?
    • 快速问题,在您向我展示的代码中(在 if 中),我如何访问 HTTP 请求值,例如标头值和正文、内容类型等?
    • HttpContextcontrollerContext 中可用。例如你可以这样做:controllerContext.HttpContext.User.Identity.Name;controllerContext.HttpContext.Request.Form["controlName"].ToString(); 等等。太酷了!
    • 太棒了,一个问题......它似乎根本不起作用,我按照你说的做了所有事情,但是进入 Action 的参数对象引用始终为 NULL:/
    猜你喜欢
    • 1970-01-01
    • 2014-10-08
    • 2019-11-24
    • 1970-01-01
    • 2016-04-28
    • 2018-02-01
    • 2020-01-25
    • 2018-06-19
    • 2018-11-18
    相关资源
    最近更新 更多