在ASP.NET 5中手动创建防伪令牌并进行验证 [英] Manual Anti-Forgery Token Creation and Validation in ASP.NET 5
问题描述
我正在使用ASP vnext和AngularJS.我已经建立了一个Web API,正在使用一些控制器,并且正在使用angular来进行一些网络魔术.
I am playing around with ASP vnext and AngularJS. I have set up a Web API, am using some controllers and am using angular to do some web-magic.
我已遵循本指南的大部分内容来启动和运行我的项目: http://stephenwalther.com/archive/2015/01/29/asp-net-5-and-angularjs-part-6-security
I have followed most of this guide to get my project up and running: http://stephenwalther.com/archive/2015/01/29/asp-net-5-and-angularjs-part-6-security
...效果很好.我已经建立了我的数据库,这样我就可以正常工作了.我也已经建立了身份框架,但是到目前为止我还没有使用它.
... which works fine. I have set up my db and such and I have things working. I have the identity framework set up too but I am not using it as of yet.
我想将一些数据发布到WebAPI.这也可以正常工作,但是现在我想在使用防伪令牌时做到这一点.我已经在Google上搜索了很多,我认为这是最有意义的: novablog
I want to post some data to the WebAPI. Which also works fine, but now I want to do it while using anti forgery tokens. I have googled a lot and I guess this makes the most sense: novablog
但是: 它使用System.Web.Helpers创建令牌并对其进行验证.它们在vnext中不再可用.我现在不知道该用什么来创建和验证令牌.
However: this uses System.Web.Helpers to create the tokens and validate them. They are not available anymore in vnext. I cannot figure out what to use to create and validate the tokens now.
有什么想法吗?
推荐答案
以下是ASP.NET 5的MusicStore示例中的一个示例:
Following is an example from the ASP.NET 5's MusicStore sample:
上述链接的摘录(请注意,如果您不喜欢上面的链接的操作,可以将[FromServices] AntiForgery antiforgery
用作操作的参数):
Snippet from the above link(Note that you can use the [FromServices] AntiForgery antiforgery
as a parameter to the action if you do no like how the link does above):
[HttpPost]
public async Task<IActionResult> RemoveFromCart(int id)
{
var formParameters = await Context.Request.ReadFormAsync();
var requestVerification = formParameters["RequestVerificationToken"];
string cookieToken = null;
string formToken = null;
if (!string.IsNullOrWhiteSpace(requestVerification))
{
var tokens = requestVerification.Split(':');
if (tokens != null && tokens.Length == 2)
{
cookieToken = tokens[0];
formToken = tokens[1];
}
}
var antiForgery = Context.RequestServices.GetService<AntiForgery>();
antiForgery.Validate(Context, new AntiForgeryTokenSet(formToken, cookieToken));
......
这篇关于在ASP.NET 5中手动创建防伪令牌并进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!