使用AJAX和MVC在标题中进行抗验证令牌验证
我需要对我的MVC项目实施抗试验验证。但是,我在服务器端遇到问题。
我正在使用@html.antiforgeryToken()
来创建令牌。 然后,我获得令牌值,并将其包括在AJAX请求中。
// Get token
var cookie = $('input[name=__RequestVerificationToken]').val();
// Ajax request
return $.ajax({
url: url,
type: 'post',
headers: {
'x-system-source': headerValue,
'x-verification-token': cookie //verification token
},
data: ko.toJSON(entity),
contentType: 'application/json',
dataType: 'json'
});
下面的代码来自Microsoft文档,但是,我不确定如何实现它。我应该使用以下方法创建一个自定义属性,并将属性添加到每个HTTP请求中?如果是这样,最好的方法是什么?是否可以为控制器级别创建属性?我也想尽可能避免重复代码。此外,是否有一种方法可以单位测试Inforgery验证功能以确保其按预期工作。
我是Web开发的新手,如果您可以提供代码样本或将我指向正确的方向,我将不胜感激。感谢您的时间。
void ValidateRequestHeader(HttpRequestMessage request)
{
string cookieToken = "";
string formToken = "";
IEnumerable<string> tokenHeaders;
if (request.Headers.TryGetValues("x-verification-token", out tokenHeaders))
{
string[] tokens = tokenHeaders.First().Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
I need to implement antiforgery validation to my MVC project. However, I am having problems with the server side.
I am using @Html.AntiForgeryToken()
to create the token.
Then i get the token value and include it in Ajax request.
// Get token
var cookie = $('input[name=__RequestVerificationToken]').val();
// Ajax request
return $.ajax({
url: url,
type: 'post',
headers: {
'x-system-source': headerValue,
'x-verification-token': cookie //verification token
},
data: ko.toJSON(entity),
contentType: 'application/json',
dataType: 'json'
});
Code below comes from microsoft documentation, however, I am not sure how to implement it. Should I create a custom attribute with the method below and add the attribute to every http request? If so, what would be the best way? Is it possible to create attribute for a controller level? I would also like to avoid repetitive code as much as possible. In addition, is there a way to unit test aniforgery validation feature to make sure that it works as expected.
I am new to the web development, and I would appreciate if you could provide code samples or point me in the right direction. Thanks for your time.
void ValidateRequestHeader(HttpRequestMessage request)
{
string cookieToken = "";
string formToken = "";
IEnumerable<string> tokenHeaders;
if (request.Headers.TryGetValues("x-verification-token", out tokenHeaders))
{
string[] tokens = tokenHeaders.First().Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论