Search code examples
c#asp.net-core.net-corecorsantiforgerytoken

ASP.NET Core API without razor pages, using separate web app for Front-End and Anti-Forgery tokens - does it make sense?


Is there any point in having to address XSRF/CSRF by the usage of Anti-Forgery tokens for a strict backend API, that in the end will be forced to do cross-site web requests with a single, specific web domain that serves static content to the users?

The Backend API uses cookies to help keep a user authenticated, hence the concerns for CSRF, but by using CORS the backend API will only accept communication with a specific domain.

Is there a problem here? And, if anti-forgery tokens do make sense, how exactly would they be used when the front-end is on an entirely separate domain? It could, be moved to a sub-domain.


Solution

  • I believe making your software secure is always good thing to do.

    CORS is not server side security feature to prevent accessing resource on the server. It is actually browser security feature to prevent loading from other origins, unless CORS on the source server specifies otherwise. This is done by pre-flight request(OPTIONS) that specifies Allow-Control-* headers.

    For example, you are hosting front-end and API on the same server/origin, but you are using fonts from Google API. Unless CORS allows to load from Google API origin, that request should be blocked by the browser.

    As it is browser feature it doesn't necessarily mean every browser supports or enforces it, thus you cannot rely on it as a server side security feature. Also requests can be done without using a browser e.g. cURL.

    Anti-forgery token on the other hand is server security feature that mitigates XSRF/CSRF attacks. Those are trying to exploit existing trust between user/browser and server and execute action without victims knowledge from attackers origin. You may feel like CORS will block any request from attackers origin, but that is not always the case as some requests don't use pre-flight before the request. Those are called simple requests. One of them is POST request which is mostly used to alter data. Without anti-forgery token attacker can exploit it and CORS is not going to help.

    To wrap it up, I would say you should use CORS to restrict browser to load data only from origins you permit it to and avoid potentially loading malicious code and use Anti-forgery token to secure write operations(POST, PUT, PATCH, DELETE methods) to mitigate XSRF/CSRF attacks.

    Additional resources:

    Cross-Origin Resource Sharing (CORS) at Mozilla

    CSRF Explained | Understanding Cross Site Request Forgery | What is XSRF? on YouTube

    CSRF protection with CORS Origin header vs. CSRF token on StackOverflow