Enabling CORS in ASP.NET Core

Another critical aspect of security is to protect our APIs from CORS calls. By default, it is not possible to use client-side code to call services that are hosted on other domains, because scam websites may use a cross-origin call to get sensitive information about users. This security restriction is called the same-origin policy.

The restrictions on the same-origin policy act on HTTP calls using the following criteria:

  • The request is made from a different domain (for example, the site at example.com calls api.com).
  • The request is enabled from a different subdomain (for example, the website at example.com calls api.example.com).
  • The request is made from a different port (for example, the site at example.com calls example.com:3001).
  • The request is made from a different protocol (for example, the https://example.com site calls http://example.com).

CORS provides a way to allow a specific domain to make client-side calls to a service hosted within a different domain. This kind of approach becomes very useful when we want to enable a customer or a third-party client to call our service without restrictions. It is also essential to note that CORS can be enabled to allow every domain. This approach must be avoided because it will enable attackers to use our API inappropriately.

ASP.NET Core provides an out-of-the-box way to enable CORS. The framework permits the creation of CORS policies using two approaches: the middleware approach and the attributes approach. As we saw in Chapter 3, Working with the Middleware Pipeline, middleware are usually implemented to develop cross-cutting logic that covers the whole web service. On the other hand, attributes are used to apply a restriction on a single action. In the same way, this approach is taken for CORS policies.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.44.108