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

前端 未结 2 2001
南旧
南旧 2021-02-06 13:46

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.

I have followed most of t

相关标签:
2条回答
  • 2021-02-06 14:11

    check out MVC Github repo, ValidateAntiForgeryTokenAttribute exists.

    And there's the asp-anti-forgerytaghelper

    0 讨论(0)
  • 2021-02-06 14:15

    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));
        ......
    
    0 讨论(0)
提交回复
热议问题