I'm using .netcore 3.0, currently i have an API that will accept external (without Antiforgery token) and internal (with Antiforgery token) call, in this case i will need to add [IgnoreAntiforgeryToken] on the api method and base on the request to determine whether to check the antiforgery token.
Would like to know is there anyway to validate the antiforgery token inside the api function? Thanks in advance.
As far as I know, if you want to call the Antiforgery class to validate the antiforgery token, you could directly call the IAntiforgery service in your api and then use ValidateRequestAsync to validate the token.
More details, you could refer to below codes:
1.Add services.AddHttpContextAccessor();
in the startup.cs ConfigureServices method
2.Add below codes in your controller:
public class HomeController : Controller
{
private readonly IAntiforgery _antiforgery;
private readonly IHttpContextAccessor _httpcontextaccessor;
public HomeController(IAntiforgery defaultAntiforgery, IHttpContextAccessor httpcontextaccessor)
{
_antiforgery = defaultAntiforgery;
_httpcontextaccessor = httpcontextaccessor;
}
public async Task<IActionResult> PrivacyAsync()
{
try
{
await _antiforgery.ValidateRequestAsync(_httpcontextaccessor.HttpContext);
}
catch (Exception)
{
throw;
}
return View();
}
}