CORS Configuration & Usage in ASP.NET Core

>

πŸ’‘ Concept Name

CORS (Cross-Origin Resource Sharing)

πŸ“˜ Quick Intro

CORS is a security feature enforced by browsers to control resource access from different origins. It prevents unauthorized cross-domain requests. ASP.NET Core provides built-in middleware to configure and enable CORS for your APIs.

🧠 Analogy / Short Story

Imagine your home is an API. CORS is like the guest list at your front door. Only people (origins) on the guest list are allowed to enter. If someone unknown (unauthorized domain) knocks, they’re blocked at the door. CORS helps APIs stay secure while still being accessible to trusted guests.

πŸ”§ Technical Explanation

CORS (Cross-Origin Resource Sharing) is implemented in ASP.NET Core via the `Microsoft.AspNetCore.Cors` middleware. You register it in `Program.cs` using `builder.Services.AddCors()` and define policies. Then apply it globally using `app.UseCors()` or at controller/action level using the `[EnableCors]` attribute. This controls access to the API from specified origins, methods, and headers.

🎯 Purpose & Use Case

  • βœ… Allow frontend apps (React, Angular) to call backend APIs from different domains
  • βœ… Enable mobile or SPA apps to access REST APIs securely
  • βœ… Control access by domain, header, and method
  • βœ… Prevent unauthorized cross-origin calls
  • βœ… Fine-grain access policy at controller/action level

πŸ’» Real Code Example

// Program.cs
builder.Services.AddCors(options =>
{
    options.AddPolicy("MyPolicy", policy =>
    {
        policy.WithOrigins("https://myfrontend.com")
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

var app = builder.Build();

app.UseCors("MyPolicy"); // Enable CORS globally
app.MapControllers();

❓ Interview Q&A

Q1: What does CORS stand for?
A: Cross-Origin Resource Sharing.

Q2: Why is CORS needed?
A: To secure APIs and control which external domains can access them.

Q3: How do you enable CORS globally?
A: Use `AddCors()` and `UseCors()` in Program.cs.

Q4: Can CORS be restricted to specific origins?
A: Yes, via `WithOrigins()` in policy definition.

Q5: How do you enable CORS on a single controller?
A: Use `[EnableCors("PolicyName")]` attribute.

Q6: What is preflight in CORS?
A: A pre-check using HTTP OPTIONS to verify CORS policy before actual request.

Q7: Is CORS a server-side or client-side feature?
A: It’s enforced by the browser (client) but configured on the server.

Q8: Can you allow all headers and methods?
A: Yes, using `.AllowAnyHeader().AllowAnyMethod()`.

Q9: What happens if CORS is not configured correctly?
A: The browser blocks the cross-origin request.

Q10: Is CORS same as CSRF protection?
A: No, both are different security mechanisms.

πŸ“ MCQs

Q1. What does CORS stand for?

  • Custom-Origin Resource Set
  • Cross-Origin Request Service
  • Cross-Origin Resource Sharing
  • Cross-Origin Route Setup

Q2. Which method registers CORS in ASP.NET Core?

  • AddCors
  • UseCorsPolicy
  • AddPolicy
  • EnableCors

Q3. Which middleware enables CORS?

  • UseCors
  • UseSecurity
  • UseHeaders
  • UseRouting

Q4. Which HTTP method is used for CORS preflight?

  • GET
  • POST
  • OPTIONS
  • PATCH

Q5. What happens if an origin is not allowed in CORS?

  • API ignores it
  • Browser blocks the request
  • Request goes through
  • Server logs it

Q6. What does AllowAnyHeader() do?

  • Allows JSON only
  • Disables headers
  • Allows all request headers
  • Blocks headers

Q7. What does AllowAnyMethod() do?

  • Allows only GET
  • Disables POST
  • Allows all HTTP methods
  • Restricts to OPTIONS

Q8. Which attribute applies CORS to a controller?

  • [CorsPolicy]
  • [AllowCross]
  • [EnableCors]
  • [CorsAllowed]

Q9. Is CORS needed for same-domain APIs?

  • Yes
  • No
  • Maybe
  • Only in HTTPS

Q10. Is CORS enforced by server or browser?

  • Server
  • Browser
  • Client-side code
  • Middleware only

πŸ’‘ Bonus Insight

Always keep your CORS policies as strict as possible. Allow only trusted domains and limit headers and methods. If you enable `AllowAnyOrigin()` with credentials, it will throw an error. Use `WithOrigins()` for secured applications.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: