SkillPilotAI

Secure your API

Login and authorization are not the whole story: an API also needs a CORS policy for its frontend, HTTPS with HSTS, a rate limiter on sensitive endpoints, tamper-proof tokens and security headers. This note shows how to implement each one in ASP.NET Core.

60.1 The problem: no CORS policy

  • The API runs on port 5060 and the React frontend on 5173: different origins.
  • A GET with an Origin header returns data, but no Access-Control-Allow-Origin header.
  • The browser's preflight OPTIONS before the PUT gets 405 Method Not Allowed.
C#
var builder = WebApplication.CreateBuilder(args);var app = builder.Build(); app.MapGet("/api/products", () => new[]{    new { Id = 1, Name = "Mixer Grinder" },    new { Id = 2, Name = "Steel Bottle" }}); app.MapPut("/api/cart/{id:int}",    (int id, CartItem item) =>        Results.NoContent()); app.Run();
Output
$ curl -i -X OPTIONS localhost:5060/api/cart/1 \  -H "Origin: http://localhost:5173" \  -H "Access-Control-Request-Method: PUT" \  -H "Access-Control-Request-Headers: content-type"HTTP/1.1 405 Method Not AllowedContent-Length: 0Server: KestrelAllow: PUT
Why the PUT was blocked
  1. 1.Browser: preflight OPTIONS + Origin (PUT / JSON body)

  2. 2.Server: no CORS policy -> 405, no Access-Control headers

  3. 3.Browser blocks: the real PUT is never sent

Fix on the server: a CORS policy

60.2 Fix: AddCors + UseCors

  • AddCors registers the services; AddPolicy("frontend") creates a named policy.
  • Allow only the frontend origin, only GET and PUT, only the Content-Type header.
  • UseCors("frontend") adds it to the pipeline; the preflight now gets 204 with the three Access-Control headers.
C#
builder.Services.AddCors(options =>{    options.AddPolicy("frontend", policy =>        policy.WithOrigins("http://localhost:5173")              .WithMethods("GET", "PUT")              .WithHeaders("Content-Type"));}); var app = builder.Build(); app.UseCors("frontend");
Output
$ curl -i -X OPTIONS localhost:5060/api/cart/1 \  -H "Origin: http://localhost:5173" \  -H "Access-Control-Request-Method: PUT" \  -H "Access-Control-Request-Headers: content-type"HTTP/1.1 204 No ContentServer: KestrelAccess-Control-Allow-Headers: Content-TypeAccess-Control-Allow-Methods: GET,PUTAccess-Control-Allow-Origin: http://localhost:5173
  • Checkpoint: the same preflight from https://evil.example also gets 204, but with no Access-Control headers, so the browser blocks it. CORS is decided by the headers, not the status code.
Output
$ curl -i -X OPTIONS localhost:5060/api/cart/1 \  -H "Origin: https://evil.example" \  -H "Access-Control-Request-Method: PUT" \  -H "Access-Control-Request-Headers: content-type"HTTP/1.1 204 No ContentServer: Kestrel

60.3 HTTPS redirect and HSTS

  • UseHttpsRedirection sends every HTTP request to HTTPS: 307 Temporary Redirect with the HTTPS Location.
  • UseHsts runs only outside development, so the demo runs in Production on both ports.
  • AddHsts: MaxAge one year, IncludeSubDomains.
  • The HSTS header is not sent on localhost by default; the demo resolves shop.local to 127.0.0.1 (and -k only because the dev cert is untrusted).
C#
builder.Services.AddHsts(options =>{    options.MaxAge = TimeSpan.FromDays(365);    options.IncludeSubDomains = true;}); var app = builder.Build(); if (!app.Environment.IsDevelopment()){    app.UseHsts();}app.UseHttpsRedirection();
Output
$ curl -i localhost:5060/api/productsHTTP/1.1 307 Temporary RedirectContent-Length: 0Server: KestrelLocation: https://localhost:7060/api/products$ curl -k -i https://shop.local:7060/api/products \  --resolve shop.local:7060:127.0.0.1HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8Server: KestrelStrict-Transport-Security: max-age=31536000; includeSubDomains

60.4 Rate limiter: 429

  • Protects endpoints like OTP from spam and brute force.
  • AddFixedWindowLimiter("otp"): 3 requests per 1-minute window.
  • RejectionStatusCode = 429; RequireRateLimiting("otp") applies it only to the OTP endpoint.
  • Four POSTs: OTP sent three times, then 429 Too Many Requests.
C#
builder.Services.AddRateLimiter(options =>{    options.RejectionStatusCode = 429;    options.AddFixedWindowLimiter("otp", limiter =>    {        limiter.PermitLimit = 3;        limiter.Window = TimeSpan.FromMinutes(1);    });}); app.UseRateLimiter(); app.MapPost("/api/otp", () => "OTP sent")    .RequireRateLimiting("otp");
Output
$ for i in 1 2 3 4; do curl -k -i -X POST \    https://localhost:7060/api/otp; doneHTTP/1.1 200 OKOTP sentHTTP/1.1 200 OKOTP sentHTTP/1.1 200 OKOTP sentHTTP/1.1 429 Too Many RequestsContent-Length: 0

60.5 Data Protection: tamper-proof tokens

  • The built-in encryption system of ASP.NET Core; it also encrypts the Identity cookie.
  • SetApplicationName + PersistKeysToFileSystem so another server finds the same keys.
  • CreateProtector("Shop.Coupon").Protect(...) turns the coupon text into an encrypted, signed token.
  • Unprotect with the same purpose gives the text back; one changed character throws CryptographicException -> 400.
C#
builder.Services.AddDataProtection()    .SetApplicationName("shop")    .PersistKeysToFileSystem(        new DirectoryInfo("keys")); app.MapGet("/api/coupon",    (IDataProtectionProvider dp) =>{    var protector =        dp.CreateProtector("Shop.Coupon");    return protector.Protect("DIWALI50:user42");}); app.MapGet("/api/redeem",    (string code, IDataProtectionProvider dp) =>{    var protector =        dp.CreateProtector("Shop.Coupon");    try    {        return Results.Ok(            protector.Unprotect(code));    }    catch (CryptographicException)    {        return Results.BadRequest("Invalid code");    }});
Output
$ c=$(curl -s -k https://localhost:7060/api/coupon)$ echo $cCfDJ8HDquKqZTmhArn0hlhrz8szLxJZ734dn2WVCJFQJG2B-FQNZ2v_nJ-4MCW80Hbwo2ivuh0q2TyuGMZwV60KH49WRrCOMB28xeafV1FWHPmDznsOLUufaWqsW8_EmnMh3Fw$ curl -k -i "https://localhost:7060/api/redeem?code=$c"HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8"DIWALI50:user42"$ bad="${c:0:40}X${c:41}"   # one character changed$ curl -k -i "https://localhost:7060/api/redeem?code=$bad"HTTP/1.1 400 Bad RequestContent-Type: application/json; charset=utf-8"Invalid code"

60.6 Security headers middleware

HeaderValueWhat it stops
X-Content-Type-OptionsnosniffThe browser guessing the content type
X-Frame-OptionsDENYLoading the page inside any iframe (clickjacking)
Content-Security-Policydefault-src 'none'Everything, for a pure JSON API
Referrer-Policyno-referrerLeaking the URL in the Referer header
C#
app.Use(async (context, next) =>{    var headers = context.Response.Headers;    headers.XContentTypeOptions = "nosniff";    headers.XFrameOptions = "DENY";    headers.ContentSecurityPolicy =        "default-src 'none'";    headers["Referrer-Policy"] = "no-referrer";    await next();});
Output
$ curl -k -i https://localhost:7060/api/productsHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8Server: KestrelX-Content-Type-Options: nosniffX-Frame-Options: DENYContent-Security-Policy: default-src 'none'Referrer-Policy: no-referrer
Middleware order
  1. 1.HTTPS: HSTS + redirect onto a secure channel

  2. 2.Headers: nosniff, CSP, frame options on every response

  3. 3.CORS: UseCors answers the preflight

  4. 4.Rate limiter: 429, or on to the endpoint

  5. 5.Endpoint runs

The order matters

60.7 Common mistakes

  • Not setting RejectionStatusCode: the limiter returns the default 503 Service Unavailable; monitoring thinks the server is down and clients retry even more. Set 429.
  • Believing UseHttpsRedirection makes an API safe: an API client already sent its first request (with the token) over plain HTTP. For a pure API, don't listen on HTTP or reject it.
  • Expecting HSTS to protect API clients: only browsers follow HSTS.
  • Allowing any origin / method / header in CORS instead of only known ones.
C#
// Wrong: default 503, looks like the server is downbuilder.Services.AddRateLimiter(options =>{    options.AddFixedWindowLimiter("otp", limiter =>    {        limiter.PermitLimit = 3;        limiter.Window = TimeSpan.FromMinutes(1);    });});// 4th POST /api/otp// HTTP/1.1 503 Service Unavailable // Right: add one line//     options.RejectionStatusCode = 429;// 4th POST /api/otp// HTTP/1.1 429 Too Many Requests

60.8 Rules for API security

  1. CORS: allow only known origins, methods and headers.
  2. Production: HTTPS + HSTS; close plain HTTP for an API.
  3. Rate limiter with 429 per IP or per user on login and OTP.
  4. Data Protection keys in shared, protected storage.
  5. Security headers from one middleware.

60.9 Interview tips

  • CORS is enforced by the browser but configured on the server: a named AddCors policy with only known origins + UseCors.
  • Production: UseHsts + UseHttpsRedirection; for a pure API, reject HTTP outright.
  • Built-in rate limiter on sensitive endpoints, with RejectionStatusCode = 429.
  • Data Protection API for tamper-proof tokens; the real protection still comes from authentication and validation.