[Vuejs]-How use `AntiForgeryToken` in Vue js

2👍

You are not forced to use __RequestVerificationToken. It is actually for MVC not when you are using SPA. Just add Antiforgery to your services and configure the cookie and header/form-data name you pass the token from. Generate an anti-forgery token in your controller and pass it to the frontend. From there pass the anti-forgery token via header/form-data that you configured before.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddAntiforgery(options =>
    {
        options.HeaderName = "X-XSRF-TOKEN";
        options.Cookie.Name = "X-XSRF-COOKIE";
    });
}

YourController.cs

public class YourController : ControllerBase
{
    private readonly IAntiforgery antiforgery;

    public YourController(IAntiforgery  antiforgery)
    {
        this.antiforgery = antiforgery;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var token = antiforgery.GetAndStoreTokens(HttpContext);
        //token.RequestToken is actually __RequestVerificationToken. 
        //Here I used cookie to send it to frontend. 
        //You might want to use json or header. 
        //Based on antiforgery config you need to pass this from frontend to your backend via X-CSRF-TOKEN Header
        Response.Cookies.Append("XSRF_TOKEN_NEED_TO_PASSED", token.RequestToken,
            new CookieOptions() { HttpOnly = false });

        ...
    }


    [HttpPost]
    public async Task<IActionResult> Post()
    {
        //Antiforgery is valid if both X-XSRF-TOKEN Header and X-XSRF-COOKIE cookie are available and correct.
        await antiforgery.ValidateRequestAsync(HttpContext);
        return Ok();
    }
}

1👍

@{
    ViewBag.Title = "Home Page";
}

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <div id="app">
            @Html.AntiForgeryToken()

            <div v-for="student in students">
                {{ student }}
            </div>
        </div>
    </div>
    <div class="col-md-4">

    </div>
    <div class="col-md-4">

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
@section scripts{
<script type="text/javascript">
    new Vue({
        el: '#app',
        data() {
            return {
                students: []
            }
        },
        mounted() {
            axios({
                method: 'post',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    url: '@Url.Content("~/api/Student")',
                })
                .then(response => (this.students = response.data ))
                .catch(function (error) { // failed request
                    console.log(error);
                });
        }
    })
</script>
}
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Helpers;
using System.Web.Http;

namespace VueWebApplication.ApiControllers
{
    public class StudentController : ApiController
    {
        /// <summary>
        /// Validate the token
        /// </summary>
        /// <param name="request"></param>
        public static void ValidateRequestHeader(HttpRequestMessage request)
        {
            string cookieToken = "";
            string formToken = "";

            if (request.Headers.TryGetValues("RequestVerificationToken", out IEnumerable<string> tokenHeaders))
            {
                cookieToken = request.Headers.GetCookies("__RequestVerificationToken")[0].ToString().Replace("__RequestVerificationToken=", "");
                formToken = tokenHeaders.First();
            }
            AntiForgery.Validate(cookieToken, formToken);
        }

        // POST api/<controller>
        public IEnumerable<string> Post(HttpRequestMessage request)
        {
            ValidateRequestHeader(request);
            return new string[] { "student1", "student2", "student3" };
        }
    }
}

Leave a comment