Overview
Hello all techy world members...
Today we are working with APIs (Application Programming Interface). So keep some questions in your mind:
- How do APIs work?
- Are they secure?
- What are the ways to secure APIs?
- How to apply restrictions with domain names, particular APIs, and API types (GET, POST, PUT, DELETE)?
Now we will talk about a trending keyword related to APIs: CORS policy.
CORS stands for Cross-Origin Resource Sharing. As per the name, it defines how we can share APIs with domains, types, etc.
In this article, we will discuss the most trending term in the API world called CORS Policy. This is particularly relevant for popular frontend frameworks like Angular, React.js, Vue.js, Next.js, etc., and how to manage the security of these APIs.
- What is CORS policy?
- Why is it necessary for APIs?
- How to implement CORS policy?
- Where can we implement it?
- Action Method level
- Controller level
- Globally
- How to disable the CORS policy?
CORS: CORS stands for Cross-Origin Resource Sharing, which means how two or more applications share resources. In the current scenario, we have web applications working alongside Android and iOS applications. Learn more in my other article.
Follow these steps to apply the CORS policy in your web API application:
- Open your Web API solution in Visual Studio.
- If you're working with an older version, open the
Startup.cs
file; for newer versions, open theProgram.cs
file. - Register the CORS policy.
- In the Startup file, locate the ConfigureServices method. Code Below Avaiable
Final Setup of Global Level
Now Working on Particular Action Method Level and Controller Level.
In the Controller level so we just same way declare the cors policy and use the policy in controller level with two approach.
- On full controller(Global level of controlletr)
- On Particular Action Method
Basic two thing is there just follow below of syntax for same thing working.
[EnableCors("Policy1")]
In this syntax we declare the policy1 is the policy name.
In the same way we declare the CORS policy on Action Method Level so we just put the before HTTP verbs.
1 Comments
Club of Developers Blog
ReplyDeletethanks for your suggestion and improving quality of the content