← Foundations path
.NETFoundations 26 / 37Reported by candidates

CORS: which websites may call the API

“What is CORS, and how do you configure it in ASP.NET Core?”

A browser rule, not a server lock: the API tells the browser which other websites' pages may read its answers.

See it

1/6The Navistar portal wants to POST JSON with a token. First the browser asks the API: allowed?

In plain words

A web page's origin is its scheme, host and port: https://portal.navistar.example is one origin, https://api.navistar.example is another. Browsers follow the same-origin policy: JavaScript on a page may send a request to another origin, but may not read the answer unless that origin says it's allowed. Without this rule, any website you visit could quietly call your bank's API with your signed-in cookies and read the reply. CORS (Cross-Origin Resource Sharing) is how the API says who is allowed: it adds the header Access-Control-Allow-Origin: https://portal.navistar.example to its responses. The browser checks it and hands the answer to the page only if the page's origin is listed. For anything beyond a simple request (a GET or HEAD, or a POST with a form or plain-text body), such as a JSON body, an header, PUT or DELETE, the browser first sends a preflight: an request asking "may I?", and sends the real request only if the answer allows it. Credentials are cookies and other sign-in details the browser attaches on its own; a response may allow them only for exact, named origins. Two things to remember. CORS protects users in browsers; it is not a lock on the API: a script or Postman ignores it, and even a blocked browser GET still runs on the server. And it is configured in middleware, so its place in the pipeline matters.

Say it in the interview

In the lending API

The policy in Program.cs. Tap Next line.

Lending.sln · where this file sits
  • src/Api/
Diagram · step 1The Navistar portal wants to POST JSON with a token. First the browser asks the API: allowed?
Program.cs · line 1 · 1 of 6Registers CORS. options => is a short inline function that receives the settings.

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

Read more: Enable CORS in ASP.NET Core · MDN: Cross-Origin Resource Sharing