Implement antiforgery in ASP.NET 8 Core Web API to prevent from CSRF attack

I have created an ASP.NET 8 Core Web API and frontend is hosted on some other domain. I want to prevent CSRF attacks that is why I want to use antiforgery in my API. I am calling the API using AJAX and I am already using Jwt tokens – I guess that will not make any affect.

This is my setup – Program.cs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
});
</code>
<code>builder.Services.AddAntiforgery(options => { options.HeaderName = "X-CSRF-TOKEN"; }); </code>
builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-CSRF-TOKEN";
});

Controller method:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[Authorize]
[Route("api/[controller]")]
[ApiController]
public class AdminController : HelperController
{
private readonly ErrorResponseService _errorResponseService;
private readonly IAntiforgery _antiforgery;
public AdminController(TruCastContext dbContext, IWebHostEnvironment hostEnvironment, TokenBlacklistService tokenBlacklistService, IConfiguration configuration, EmailService emailService, ErrorResponseService errorResponseService, IAntiforgery antiforgery, ILogger<AdminController> logger)
{
_dbContext = dbContext;
_errorResponseService = errorResponseService;
_antiforgery = antiforgery;
}
// POST: Get User and Channel Counts
[AllowAnonymous]
[HttpPost]
[Route("GetUserAndChannelCounts")]
public IActionResult GetUserAndChannelCounts()
{
try
{
var token = _antiforgery.GetTokens(HttpContext).RequestToken;
var tokenFromHeader = Request.Headers["X-CSRF-TOKEN"].ToString();
if (string.IsNullOrEmpty(tokenFromHeader))
{
return StatusCode(400, new { Message = "No anti-forgery token found in request header" });
}
// Perform token validation
if (!_antiforgery.IsRequestValidAsync(HttpContext).Result)
{
return StatusCode(400, new { Message = "Invalid anti-forgery token" });
}
var counts = new Count
{
UserTotalCount = _dbContext.UserDetails.Count(),
UserActiveCount = _dbContext.UserDetails.Count(u => u.IsActive),
UserInactiveCount = _dbContext.UserDetails.Count(u => !u.IsActive),
ChannelTotalCount = _dbContext.ChannelDetails.Count(),
ChannelActiveCount = _dbContext.ChannelDetails.Count(c => c.IsActive),
ChannelInactiveCount = _dbContext.ChannelDetails.Count(c => !c.IsActive)
};
// success response
var successResponse = new
{
Status = 200,
Message = "Count fetched successfully",
Details = counts
};
return Ok(successResponse);
}
catch (Exception ex)
{
var errorResponse = _errorResponseService.CreateErrorResponse(500, "Internal Server Error: " + ex.Message);
return StatusCode(500, errorResponse);
}
}
}
</code>
<code>[Authorize] [Route("api/[controller]")] [ApiController] public class AdminController : HelperController { private readonly ErrorResponseService _errorResponseService; private readonly IAntiforgery _antiforgery; public AdminController(TruCastContext dbContext, IWebHostEnvironment hostEnvironment, TokenBlacklistService tokenBlacklistService, IConfiguration configuration, EmailService emailService, ErrorResponseService errorResponseService, IAntiforgery antiforgery, ILogger<AdminController> logger) { _dbContext = dbContext; _errorResponseService = errorResponseService; _antiforgery = antiforgery; } // POST: Get User and Channel Counts [AllowAnonymous] [HttpPost] [Route("GetUserAndChannelCounts")] public IActionResult GetUserAndChannelCounts() { try { var token = _antiforgery.GetTokens(HttpContext).RequestToken; var tokenFromHeader = Request.Headers["X-CSRF-TOKEN"].ToString(); if (string.IsNullOrEmpty(tokenFromHeader)) { return StatusCode(400, new { Message = "No anti-forgery token found in request header" }); } // Perform token validation if (!_antiforgery.IsRequestValidAsync(HttpContext).Result) { return StatusCode(400, new { Message = "Invalid anti-forgery token" }); } var counts = new Count { UserTotalCount = _dbContext.UserDetails.Count(), UserActiveCount = _dbContext.UserDetails.Count(u => u.IsActive), UserInactiveCount = _dbContext.UserDetails.Count(u => !u.IsActive), ChannelTotalCount = _dbContext.ChannelDetails.Count(), ChannelActiveCount = _dbContext.ChannelDetails.Count(c => c.IsActive), ChannelInactiveCount = _dbContext.ChannelDetails.Count(c => !c.IsActive) }; // success response var successResponse = new { Status = 200, Message = "Count fetched successfully", Details = counts }; return Ok(successResponse); } catch (Exception ex) { var errorResponse = _errorResponseService.CreateErrorResponse(500, "Internal Server Error: " + ex.Message); return StatusCode(500, errorResponse); } } } </code>
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class AdminController : HelperController
{
    private readonly ErrorResponseService _errorResponseService;
    private readonly IAntiforgery _antiforgery;

    public AdminController(TruCastContext dbContext, IWebHostEnvironment hostEnvironment, TokenBlacklistService tokenBlacklistService, IConfiguration configuration, EmailService emailService, ErrorResponseService errorResponseService, IAntiforgery antiforgery, ILogger<AdminController> logger)
    {
        _dbContext = dbContext;
        _errorResponseService = errorResponseService;
        _antiforgery = antiforgery;
    }

    // POST: Get User and Channel Counts
    [AllowAnonymous]
    [HttpPost]
    [Route("GetUserAndChannelCounts")]
    public IActionResult GetUserAndChannelCounts()
    {
        try
        {
            var token = _antiforgery.GetTokens(HttpContext).RequestToken;

            var tokenFromHeader = Request.Headers["X-CSRF-TOKEN"].ToString();

            if (string.IsNullOrEmpty(tokenFromHeader))
            {
                return StatusCode(400, new { Message = "No anti-forgery token found in request header" });
            }
 
            // Perform token validation
            if (!_antiforgery.IsRequestValidAsync(HttpContext).Result)
            {
                return StatusCode(400, new { Message = "Invalid anti-forgery token" });
            }

            var counts = new Count
                {
                    UserTotalCount = _dbContext.UserDetails.Count(),
                    UserActiveCount = _dbContext.UserDetails.Count(u => u.IsActive),
                    UserInactiveCount = _dbContext.UserDetails.Count(u => !u.IsActive),
                    ChannelTotalCount = _dbContext.ChannelDetails.Count(),
                    ChannelActiveCount = _dbContext.ChannelDetails.Count(c => c.IsActive),
                    ChannelInactiveCount = _dbContext.ChannelDetails.Count(c => !c.IsActive)
                };

            // success response
            var successResponse = new
                {
                    Status = 200,
                    Message = "Count fetched successfully",
                    Details = counts
                };

            return Ok(successResponse);
        }
        catch (Exception ex)
        {
            var errorResponse = _errorResponseService.CreateErrorResponse(500, "Internal Server Error: " + ex.Message);
            return StatusCode(500, errorResponse);
        }
    }
}

Dashboard.cshtml:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><form id="dashboardform" asp-antiforgery="true">
@Html.AntiForgeryToken() <!-- this generates the anti-forgery token -->
</form>
</code>
<code><form id="dashboardform" asp-antiforgery="true"> @Html.AntiForgeryToken() <!-- this generates the anti-forgery token --> </form> </code>
<form id="dashboardform" asp-antiforgery="true">
    @Html.AntiForgeryToken()  <!-- this generates the anti-forgery token -->
</form>

Dashboard.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$(document).ready(function () {
let connection = getAPIConnection();
let jwtToken = localStorage.getItem("jwtToken");
GetCount();
function GetCount() {
isLoading = true;
var url = connection + "api/Admin/Count";
// Get the Anti-Forgery token from the hidden input field
var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();
console.log("Anti-Forgery Token: ", antiForgeryToken); // Check if the token is populated
$.ajax({
url: url,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + jwtToken,
'X-CSRF-TOKEN': antiForgeryToken // Include Anti-Forgery token
},
success: function (response) {
if (response.Status === 200) {
console.log("Forgery Token: ", antiForgeryToken)
// Access the counts directly from the Details object
$('#tcCount').text(response.Details.ChannelTotalCount);
} else if (response.Status === 404) {
console.error("Counts not found");
} else {
console.error("Failed to retrieve channel details");
}
}
,
error: function (xhr, status, error) {
console.error("Error occurred: ", error);
}
});
}
});
</code>
<code>$(document).ready(function () { let connection = getAPIConnection(); let jwtToken = localStorage.getItem("jwtToken"); GetCount(); function GetCount() { isLoading = true; var url = connection + "api/Admin/Count"; // Get the Anti-Forgery token from the hidden input field var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val(); console.log("Anti-Forgery Token: ", antiForgeryToken); // Check if the token is populated $.ajax({ url: url, method: 'POST', headers: { 'Authorization': 'Bearer ' + jwtToken, 'X-CSRF-TOKEN': antiForgeryToken // Include Anti-Forgery token }, success: function (response) { if (response.Status === 200) { console.log("Forgery Token: ", antiForgeryToken) // Access the counts directly from the Details object $('#tcCount').text(response.Details.ChannelTotalCount); } else if (response.Status === 404) { console.error("Counts not found"); } else { console.error("Failed to retrieve channel details"); } } , error: function (xhr, status, error) { console.error("Error occurred: ", error); } }); } }); </code>
$(document).ready(function () {
    let connection = getAPIConnection();
    let jwtToken = localStorage.getItem("jwtToken");
    GetCount();
    function GetCount() {
        isLoading = true;
        var url = connection + "api/Admin/Count";

        // Get the Anti-Forgery token from the hidden input field
        var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();
            console.log("Anti-Forgery Token: ", antiForgeryToken);  // Check if the token is populated
        
        $.ajax({
            url: url,
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + jwtToken,
                'X-CSRF-TOKEN': antiForgeryToken // Include Anti-Forgery token
            },
             
            success: function (response) {
                if (response.Status === 200) {
                    console.log("Forgery Token: ", antiForgeryToken)
                    // Access the counts directly from the Details object
                    $('#tcCount').text(response.Details.ChannelTotalCount);
                } else if (response.Status === 404) {
                    console.error("Counts not found");
                } else {
                    console.error("Failed to retrieve channel details");
                }
            }
,
            error: function (xhr, status, error) {
                console.error("Error occurred: ", error);
            }
        });
    }
});

I added antiforgery in program.cs file and added manual antiforgery in my controller method to validate which is being sent through frontend header in correct format, but I get this error all the time:

Invalid Anti-Forgery Token

I am expecting that API should return the data instead of an error

New contributor

Sayed Asad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Implement antiforgery in ASP.NET 8 Core Web API to prevent from CSRF attack

I have created an ASP.NET 8 Core Web API and frontend is hosted on some other domain. I want to prevent CSRF attacks that is why I want to use antiforgery in my API. I am calling the API using AJAX and I am already using Jwt tokens – I guess that will not make any affect.

This is my setup – Program.cs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
});
</code>
<code>builder.Services.AddAntiforgery(options => { options.HeaderName = "X-CSRF-TOKEN"; }); </code>
builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-CSRF-TOKEN";
});

Controller method:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[Authorize]
[Route("api/[controller]")]
[ApiController]
public class AdminController : HelperController
{
private readonly ErrorResponseService _errorResponseService;
private readonly IAntiforgery _antiforgery;
public AdminController(TruCastContext dbContext, IWebHostEnvironment hostEnvironment, TokenBlacklistService tokenBlacklistService, IConfiguration configuration, EmailService emailService, ErrorResponseService errorResponseService, IAntiforgery antiforgery, ILogger<AdminController> logger)
{
_dbContext = dbContext;
_errorResponseService = errorResponseService;
_antiforgery = antiforgery;
}
// POST: Get User and Channel Counts
[AllowAnonymous]
[HttpPost]
[Route("GetUserAndChannelCounts")]
public IActionResult GetUserAndChannelCounts()
{
try
{
var token = _antiforgery.GetTokens(HttpContext).RequestToken;
var tokenFromHeader = Request.Headers["X-CSRF-TOKEN"].ToString();
if (string.IsNullOrEmpty(tokenFromHeader))
{
return StatusCode(400, new { Message = "No anti-forgery token found in request header" });
}
// Perform token validation
if (!_antiforgery.IsRequestValidAsync(HttpContext).Result)
{
return StatusCode(400, new { Message = "Invalid anti-forgery token" });
}
var counts = new Count
{
UserTotalCount = _dbContext.UserDetails.Count(),
UserActiveCount = _dbContext.UserDetails.Count(u => u.IsActive),
UserInactiveCount = _dbContext.UserDetails.Count(u => !u.IsActive),
ChannelTotalCount = _dbContext.ChannelDetails.Count(),
ChannelActiveCount = _dbContext.ChannelDetails.Count(c => c.IsActive),
ChannelInactiveCount = _dbContext.ChannelDetails.Count(c => !c.IsActive)
};
// success response
var successResponse = new
{
Status = 200,
Message = "Count fetched successfully",
Details = counts
};
return Ok(successResponse);
}
catch (Exception ex)
{
var errorResponse = _errorResponseService.CreateErrorResponse(500, "Internal Server Error: " + ex.Message);
return StatusCode(500, errorResponse);
}
}
}
</code>
<code>[Authorize] [Route("api/[controller]")] [ApiController] public class AdminController : HelperController { private readonly ErrorResponseService _errorResponseService; private readonly IAntiforgery _antiforgery; public AdminController(TruCastContext dbContext, IWebHostEnvironment hostEnvironment, TokenBlacklistService tokenBlacklistService, IConfiguration configuration, EmailService emailService, ErrorResponseService errorResponseService, IAntiforgery antiforgery, ILogger<AdminController> logger) { _dbContext = dbContext; _errorResponseService = errorResponseService; _antiforgery = antiforgery; } // POST: Get User and Channel Counts [AllowAnonymous] [HttpPost] [Route("GetUserAndChannelCounts")] public IActionResult GetUserAndChannelCounts() { try { var token = _antiforgery.GetTokens(HttpContext).RequestToken; var tokenFromHeader = Request.Headers["X-CSRF-TOKEN"].ToString(); if (string.IsNullOrEmpty(tokenFromHeader)) { return StatusCode(400, new { Message = "No anti-forgery token found in request header" }); } // Perform token validation if (!_antiforgery.IsRequestValidAsync(HttpContext).Result) { return StatusCode(400, new { Message = "Invalid anti-forgery token" }); } var counts = new Count { UserTotalCount = _dbContext.UserDetails.Count(), UserActiveCount = _dbContext.UserDetails.Count(u => u.IsActive), UserInactiveCount = _dbContext.UserDetails.Count(u => !u.IsActive), ChannelTotalCount = _dbContext.ChannelDetails.Count(), ChannelActiveCount = _dbContext.ChannelDetails.Count(c => c.IsActive), ChannelInactiveCount = _dbContext.ChannelDetails.Count(c => !c.IsActive) }; // success response var successResponse = new { Status = 200, Message = "Count fetched successfully", Details = counts }; return Ok(successResponse); } catch (Exception ex) { var errorResponse = _errorResponseService.CreateErrorResponse(500, "Internal Server Error: " + ex.Message); return StatusCode(500, errorResponse); } } } </code>
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class AdminController : HelperController
{
    private readonly ErrorResponseService _errorResponseService;
    private readonly IAntiforgery _antiforgery;

    public AdminController(TruCastContext dbContext, IWebHostEnvironment hostEnvironment, TokenBlacklistService tokenBlacklistService, IConfiguration configuration, EmailService emailService, ErrorResponseService errorResponseService, IAntiforgery antiforgery, ILogger<AdminController> logger)
    {
        _dbContext = dbContext;
        _errorResponseService = errorResponseService;
        _antiforgery = antiforgery;
    }

    // POST: Get User and Channel Counts
    [AllowAnonymous]
    [HttpPost]
    [Route("GetUserAndChannelCounts")]
    public IActionResult GetUserAndChannelCounts()
    {
        try
        {
            var token = _antiforgery.GetTokens(HttpContext).RequestToken;

            var tokenFromHeader = Request.Headers["X-CSRF-TOKEN"].ToString();

            if (string.IsNullOrEmpty(tokenFromHeader))
            {
                return StatusCode(400, new { Message = "No anti-forgery token found in request header" });
            }
 
            // Perform token validation
            if (!_antiforgery.IsRequestValidAsync(HttpContext).Result)
            {
                return StatusCode(400, new { Message = "Invalid anti-forgery token" });
            }

            var counts = new Count
                {
                    UserTotalCount = _dbContext.UserDetails.Count(),
                    UserActiveCount = _dbContext.UserDetails.Count(u => u.IsActive),
                    UserInactiveCount = _dbContext.UserDetails.Count(u => !u.IsActive),
                    ChannelTotalCount = _dbContext.ChannelDetails.Count(),
                    ChannelActiveCount = _dbContext.ChannelDetails.Count(c => c.IsActive),
                    ChannelInactiveCount = _dbContext.ChannelDetails.Count(c => !c.IsActive)
                };

            // success response
            var successResponse = new
                {
                    Status = 200,
                    Message = "Count fetched successfully",
                    Details = counts
                };

            return Ok(successResponse);
        }
        catch (Exception ex)
        {
            var errorResponse = _errorResponseService.CreateErrorResponse(500, "Internal Server Error: " + ex.Message);
            return StatusCode(500, errorResponse);
        }
    }
}

Dashboard.cshtml:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><form id="dashboardform" asp-antiforgery="true">
@Html.AntiForgeryToken() <!-- this generates the anti-forgery token -->
</form>
</code>
<code><form id="dashboardform" asp-antiforgery="true"> @Html.AntiForgeryToken() <!-- this generates the anti-forgery token --> </form> </code>
<form id="dashboardform" asp-antiforgery="true">
    @Html.AntiForgeryToken()  <!-- this generates the anti-forgery token -->
</form>

Dashboard.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$(document).ready(function () {
let connection = getAPIConnection();
let jwtToken = localStorage.getItem("jwtToken");
GetCount();
function GetCount() {
isLoading = true;
var url = connection + "api/Admin/Count";
// Get the Anti-Forgery token from the hidden input field
var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();
console.log("Anti-Forgery Token: ", antiForgeryToken); // Check if the token is populated
$.ajax({
url: url,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + jwtToken,
'X-CSRF-TOKEN': antiForgeryToken // Include Anti-Forgery token
},
success: function (response) {
if (response.Status === 200) {
console.log("Forgery Token: ", antiForgeryToken)
// Access the counts directly from the Details object
$('#tcCount').text(response.Details.ChannelTotalCount);
} else if (response.Status === 404) {
console.error("Counts not found");
} else {
console.error("Failed to retrieve channel details");
}
}
,
error: function (xhr, status, error) {
console.error("Error occurred: ", error);
}
});
}
});
</code>
<code>$(document).ready(function () { let connection = getAPIConnection(); let jwtToken = localStorage.getItem("jwtToken"); GetCount(); function GetCount() { isLoading = true; var url = connection + "api/Admin/Count"; // Get the Anti-Forgery token from the hidden input field var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val(); console.log("Anti-Forgery Token: ", antiForgeryToken); // Check if the token is populated $.ajax({ url: url, method: 'POST', headers: { 'Authorization': 'Bearer ' + jwtToken, 'X-CSRF-TOKEN': antiForgeryToken // Include Anti-Forgery token }, success: function (response) { if (response.Status === 200) { console.log("Forgery Token: ", antiForgeryToken) // Access the counts directly from the Details object $('#tcCount').text(response.Details.ChannelTotalCount); } else if (response.Status === 404) { console.error("Counts not found"); } else { console.error("Failed to retrieve channel details"); } } , error: function (xhr, status, error) { console.error("Error occurred: ", error); } }); } }); </code>
$(document).ready(function () {
    let connection = getAPIConnection();
    let jwtToken = localStorage.getItem("jwtToken");
    GetCount();
    function GetCount() {
        isLoading = true;
        var url = connection + "api/Admin/Count";

        // Get the Anti-Forgery token from the hidden input field
        var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();
            console.log("Anti-Forgery Token: ", antiForgeryToken);  // Check if the token is populated
        
        $.ajax({
            url: url,
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + jwtToken,
                'X-CSRF-TOKEN': antiForgeryToken // Include Anti-Forgery token
            },
             
            success: function (response) {
                if (response.Status === 200) {
                    console.log("Forgery Token: ", antiForgeryToken)
                    // Access the counts directly from the Details object
                    $('#tcCount').text(response.Details.ChannelTotalCount);
                } else if (response.Status === 404) {
                    console.error("Counts not found");
                } else {
                    console.error("Failed to retrieve channel details");
                }
            }
,
            error: function (xhr, status, error) {
                console.error("Error occurred: ", error);
            }
        });
    }
});

I added antiforgery in program.cs file and added manual antiforgery in my controller method to validate which is being sent through frontend header in correct format, but I get this error all the time:

Invalid Anti-Forgery Token

I am expecting that API should return the data instead of an error

New contributor

Sayed Asad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật