Enabling CORS in .Net Core Web API
Cross-Origin Resource Sharing (CORS)
Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site.
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources
Cross Origin Resource Sharing (CORS):
- Is a W3C standard that allows a server to relax the same-origin policy.
- Is not a security feature, CORS relaxes security. An API is not safer by allowing CORS. For more information, see How CORS works.
- Allows a server to explicitly allow some cross-origin requests while rejecting others.
- Is safer and more flexible than earlier techniques, such as JSONP.
If we try to consume the same API from an Ajax call (Refer privacy page for this implementation - http://localhost:5176/Home/Privacy), we get the below error.
Here the web application is running on the host http://localhost:5176/ which is trying to call an API from http://localhost:5157/ (not from same domain) and that's why it is not working.
- An important point to observe here is that with origins takes an array of source, so we can provide multiple URLs here and the API will work from all requests coming from any of these sources.
- We can also use WithHeaders (to provide the header name) and WithMethods (to specify Http method names) to control what is allowed or not
For some CORS requests, the browser sends an additional OPTIONS request before making the actual request. This request is called a preflight request. The browser can skip the preflight request if all the following conditions are true:
- The request method is GET, HEAD, or POST.
- The app doesn't set request headers other than
Accept
,Accept-Language
,Content-Language
,Content-Type
, orLast-Event-ID
. - The
Content-Type
header, if set, has one of the following values:application/x-www-form-urlencoded
multipart/form-data
text/plain
Comments
Post a Comment