Search code examples
c#asp.net-coreantiforgerytoken

How to generate an anti forgery token manually in ASP.NET Core


I need to generate an anti forgery token manually!

How can I generate this?

public class TokenController : Controller
{
    [HttpPost]
    [IgnoreAntiforgeryToken]
    public ActionResult Generate()
    {
        var token = "";

        //Generate a token

        return Json(token);
    }
}

Solution

  • I think you can inject an IAntiforgery instance to your controller (docs).

    public class TokenController : Controller
    {
        private readonly IAntiforgery _antiforgery;
    
        public TokenController(IAntiforgery antiforgery)
        {
            _antiforgery = antiforgery;
        }
    
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public ActionResult Generate()
        {
            var token = "";
    
            //Generate a token
            var tokenSet = _antiforgery.GetTokens(HttpContext);
    
            return Json(token);
        }
    }