Antiforgery Token Validation When Angular and HTTP API Runs on the Same Server
In this post, I explain how to overcome AntiForgery Token validation for HTTP requests in the ABP Angular project. This issue happens when the Angular and HTTP API projects are running on the same domain. See the simple solution in this post.
When dealing with medium to large-scale projects, it is customary to separate Angular and API into two distinct sites for clear functional division and efficient team collaboration. However, for smaller projects, deploying Angular and API under the same site (i.e., the same domain) is also a viable option.
Due to the built-in CSRF/XSRF and anti-forgery systems in the Abp project’s API, running Abp Angular and Abp API in the same domain may result in issues. Specifically, when Angular sends Delete, Put, or Post requests to the API, it may encounter a 400 HTTP status code error without meaningful error logs.
Recently, I faced several hours of challenges while deploying a small personal project with Abp Angular and Abp API in the same domain. Despite being proficient in separating Abp Angular and Abp API in previous deployments, I mistakenly assumed the issue was not in the program but perhaps related to the server environment. This misguided confidence led to a considerable waste of valuable time in the wrong direction.
Only when running Abp Angular and Abp API on the same domain locally did I identify the true error:
The required antiforgery header value “RequestVerificationToken” is not present.
I suddenly realized that the CSRF/XSRF anti-forgery system in the API was blocking requests from the Angular program within the same domain.
Upon researching, I discovered that Abp team member @hikalkan had already provided a solution back in 2020 in the Abp Framework issues, as detailed in https://github.com/abpframework/abp/pull/5728. Additionally, the Abp Framework CSRF/XSRF & Anti Forgery System documentation offers comprehensive guidance on deploying Abp Angular and Abp API in the same domain.
The solution is straightforward — simply remove the domain from the API URL, as shown in the following code snippet:
export const environment = {
production: true,
// ....
apis: {
default: {
url: '', // <- should be an empty string, not '/'
// ...
},
},
} as Config.Environment;
I extend my sincere gratitude to the Abp team for their selfless dedication in developing the Abp Framework and crafting detailed documentation. This experience serves as a reminder not to be overly confident when facing issues, always maintaining sensitivity to possibilities, and leveraging team and documentation resources for more efficient resolution of technical challenges.