【发布时间】:2016-09-20 11:11:26
【问题描述】:
我有一个类用于执行防伪令牌验证,其中有效负载是 Json。这个类看起来像这样(来自 Phil Haacked):
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (ReferenceEquals(filterContext, null)) throw new ArgumentNullException("filterContext");
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes
// to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = ReferenceEquals(antiForgeryCookie, null) ? null : antiForgeryCookie.Value;
AntiForgery.Validate(cookieValue, request.Headers[AntiForgeryConfig.CookieName]);
}
else
{
new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
}
}
}
}
这是我使用它的第一个 Angular 项目,它并没有在我期望的地方抛出异常。例如,标头中的值与 cookie 中的值不同,并且对 AntiForgery.Validate 的调用无一例外地继续进行。
防伪令牌在 shell 视图中呈现(即 Index.cshtml),并添加到 Angular 模块运行函数的标头中:
// Handle routing errors and success events
theApp.run(['$http', '$route', '$rootScope', '$q', 'routeOverlord',
function ($http, $route, $rootScope, $q, routeOverlord) {
// Include $route to kick start the router.
routeOverlord.setRoutingHandlers();
// Include AntiForgeryToken to prevent CSRF attacks
$http.defaults.headers.common['__RequestVerificationToken'] = angular.element('input[name="__RequestVerificationToken"]').val();
}]);
这是众所周知的事情吗?如果需要,很高兴提供 cookie 和标头中不同字符串的 Fiddler 屏幕截图。
干杯
【问题讨论】:
-
没时间测试,但是
AntiForgery.Validate(cookieValue, request.Headers[AntiForgeryConfig.CookieName]);这一行不应该是在寻找一个名称为__RequestVerificationToken而不是AntiForgeryConfig.CookieName的标题 -
@SBurris AntiForgeryConfig.CookieName 是该框架类上的静态字符串,解析为 __RequestVerificationToken
标签: asp.net asp.net-mvc-5 antiforgerytoken