wasAsked.

explain implantation of CORS

PwC · Full Stack Developer · technical

Published

Year not specified · Authentication & Security

Community answers

Posted by wasAsked editorial collection

CORS (Cross-Origin Resource Sharing) is a browser mechanism that lets a server allow web pages from other origins (scheme, host and port) to read its responses. By default, browsers block JavaScript from reading cross-origin responses (the Same-Origin Policy). How it works - Simple requests (GET or POST with simple headers): the browser sends an Origin header; if the response includes Access-Control-Allow-Origin matching that origin, the script can read the response. - Preflight requests: for other methods (PUT, DELETE), custom headers (Authorization, Content-Type: application/json) or credentials, the browser first sends an OPTIONS request with Access-Control-Request-Method and Access-Control-Request-Headers. The server answers which methods, headers and origins are allowed, and Access-Control-Max-Age caches that answer. Implementation in ASP.NET Core builder.Services.AddCors(options => { options.AddPolicy("Frontend", policy => policy .WithOrigins("https://app.example.com", "http://localhost:4200") .WithMethods("GET", "POST", "PUT", "DELETE") .WithHeaders("Authorization", "Content-Type") .AllowCredentials()); // only if you use cookies }); app.UseRouting(); app.UseCors("Frontend"); // before authentication, authorization and endpoints app.UseAuthentication(); app.UseAuthorization(); You can also apply it per endpoint with [EnableCors("Frontend")] or RequireCors("Frontend"). Rules and pitfalls - Never combine AllowAnyOrigin with AllowCredentials; ASP.NET Core forbids it, and reflecting any origin with credentials is a security hole. - Use exact origins from configuration per environment rather than wildcards. - Middleware order matters: UseCors must come before the endpoints, otherwise preflight requests fail. - CORS errors appear in the browser console; tools like Postman ignore CORS because they are not browsers. - If the frontend and API share the same origin (for example through a reverse proxy), you may not need CORS at all. Security understanding interviewers look for: CORS is not authentication or authorization. It only controls which browser pages may read responses; the API must still authenticate and authorize every request, and server-to-server calls are not affected by CORS.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics