runtime loading of ValidateAntiForgeryToken Salt value

与世无争的帅哥 提交于 2019-11-28 00:31:05

The Salt property is meant to be a compile-time constant. It's simply a way to link a particular form to a particular action method. For example, if you have a login form, you may wish to use the salt "Login" for this form so that a token that was valid for the login form can't be used for the change password form, etc.

In all cases, the app's machine key is automatically used as an additional salt value. So an anti-XSRF token for one application can't be used for another application, even if both salt values read "Login". The machine key is settable in the Web.config <machineKey> section.

I had the requirement to have different salts for different customers. In this case, I used Dixin's solution for injecting the salt at runtime.

Anti Forgery Request Recipes For ASP.NET MVC and AJAX at the section titled "Specify non-constant salt in runtime".

Decorate your Controllers with a new attribute:

[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post)]
public class ProductController : Controller
{     
    // Only HTTP POST requests are validated.
}

This new attribute is defined as:

public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter
{
    public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs)
    {
        this._verbs = new AcceptVerbsAttribute(verbs);
        this._validator = new ValidateAntiForgeryTokenAttribute()
            {
                //load from web.config or anywhere else
                Salt = Configurations.AntiForgeryTokenSalt
            };
    }

    // Other members.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!