Manual Anti-Forgery Token Creation and Validation in ASP.NET 5

余生颓废 提交于 2019-12-03 08:56:36

Following is an example from the ASP.NET 5's MusicStore sample:

https://github.com/aspnet/MusicStore/blob/master/src/MusicStore/Controllers/ShoppingCartController.cs#L62

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));
    ......

check out MVC Github repo, ValidateAntiForgeryTokenAttribute exists.

And there's the asp-anti-forgerytaghelper

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