A security-focused code review of an ASP.NET Core endpoint with SQL injection, broken object-level authorisation, an open redirect and verbose error disclosure, ranked by severity with a full rewrite.
I'd rank the findings by impact. 1. SQL injection: the customer name and ORDER BY column are concatenated, so one request can read or change any data; fix with parameters and an allow-listed sort map. 2. Broken object-level authorisation (IDOR): Void loads any invoice by id, so any user can void any customer's invoice; fix by scoping the query to the caller's customer (or IAuthorizationService with a resource policy) and returning 404. 3. Open redirect: Redirect(returnUrl) enables phishing; use LocalRedirect with Url.IsLocalUrl. 4. Verbose errors: ex.ToString() leaks stack traces, SQL and schema; use UseExceptionHandler + ProblemDetails. Plus SELECT * over-exposure. The first two block the merge; I'd ask for a test per finding.
"I'd review it the way an attacker would read it: what's the worst thing one request can do? The search action builds SQL by concatenation, including the sort column, so that's SQL injection: read every invoice, possibly modify data depending on the login's permissions. That's the top blocker. Close behind is
Void: it takes an id, loads the invoice and changes it with no check that the caller owns it. That's broken object-level authorisation, number one on the OWASP API list, and it's a data-integrity issue across customers. Both block the merge.Then the redirect:
Redirect(returnUrl)from the query string is an open redirect, a phishing aid on our trusted domain. And the catch block returnsex.ToString(), which hands attackers stack traces, SQL text and table names, the exact feedback that makes the injection easy to exploit. At [company] I reviewed [a very similar controller in an internal billing tool]; the [IDOR] had shipped and was found by [a customer]. We fixed it with tenant-scoped queries and added an authorisation test for every endpoint, which [found two more].For the rewrite: EF Core with a projection and an allow-listed sort map; the invoice loaded with
Where(i => i.Id == id && i.CustomerId == callerCustomerId), returning 404 rather than 403 so ids can't be probed;LocalRedirectwith a safe fallback, or better, an API that returns 204 and lets the client navigate; and no try/catch at all in the action, because the global exception handler returns ProblemDetails with a trace id. The mistake I see in reviews is listing these as equal 'nits'. Ranking them is the point: two of them are breach-level, two are hardening."
[ApiController]
[Route("api/invoices")]
[Authorize]
public class InvoicesController(IConfiguration config, BillingDb db) : ControllerBase
{
[HttpGet("search")]
public IActionResult Search(string customer, string sort)
{
try
{
using var conn = new SqlConnection(config.GetConnectionString("Billing"));
var sql = "SELECT * FROM Invoices WHERE CustomerName LIKE '%" + customer + "%' " + // 1
"ORDER BY " + sort; // 1
var rows = conn.Query(sql); // 5 SELECT *
return Ok(rows);
}
catch (Exception ex)
{
return StatusCode(500, ex.ToString()); // 4
}
}
[HttpPost("{id:int}/void")]
public async Task<IActionResult> Void(int id, [FromQuery] string returnUrl)
{
var invoice = await db.Invoices.FindAsync(id); // 2 no ownership check
invoice!.Status = InvoiceStatus.Voided;
await db.SaveChangesAsync();
return Redirect(returnUrl); // 3
}
}
| # | Severity | Finding | Impact | Fix |
|---|---|---|---|---|
| 1 | Critical | SQL injection via customer and sort |
Read or modify any data the login can reach | Parameters + allow-listed sort |
| 2 | Critical | BOLA/IDOR on Void |
Any user voids any customer's invoice | Scope query to caller's customer; 404 |
| 3 | Medium | Open redirect via returnUrl |
Phishing on our domain | LocalRedirect + Url.IsLocalUrl, or no redirect in an API |
| 4 | Medium | ex.ToString() to client |
Leaks stack, SQL, schema; aids finding 1 | Global exception handler + ProblemDetails |
| 5 | Low | SELECT * returned directly |
Over-exposes columns (and future columns) | Project to a DTO |
| — | Low | invoice! null-forgiving |
500 instead of 404 | Handle null |
(See the code example section for the full, compilable version.) Key points: EF Core with AsNoTracking and a DTO projection, EF.Functions.Like with a parameter, a Dictionary mapping API sort names to expressions, a ICurrentCustomer abstraction from claims, tenant-scoped loading, NoContent() for the API, and no local try/catch.
| Comment | Type |
|---|---|
SQL injection in Search |
Blocking, with a failing test showing sort=Id;-- is rejected |
Missing ownership check in Void |
Blocking, with an integration test: user A can't void user B's invoice (404) |
| Open redirect | Blocking for a browser-facing endpoint; suggest removing the redirect from the API |
| Error disclosure | Blocking: remove local catch, rely on UseExceptionHandler |
SELECT *, null handling |
Suggested |
Then the systemic follow-up: enable EF1002 and security analysers as errors, add an authorisation test pattern for every endpoint that takes an id, a CI grep for Redirect( with request data and string-built SQL, and a short checklist in the PR template.
Applying the same review checklist to a billing service's 60 endpoints found 4 IDOR-style handlers and 2 string-built queries; per-endpoint authorisation tests (about 120 small tests running in under 20 seconds with WebApplicationFactory) have caught 3 regressions since.
Checks that the candidate spots every security flaw, ranks them by real impact, writes a correct rewrite and turns the review into lasting guardrails.
Green flags
Red flags
[Authorize] is presentCan one request... -> severity
run arbitrary SQL / code? -> Critical (injection)
read or change another customer's data? -> Critical (BOLA, missing authz)
trick users into harm on our domain? -> Medium (open redirect, clickjacking)
learn how to attack us better? -> Medium/Low (verbose errors, versions)
degrade quality but not security? -> Low (SELECT *, nullability)
Ranking matters because reviewers and teams have limited attention; a review that lists eight equal comments gets the easy ones fixed first.
[Authorize] checks who you are, not what you may touch. Object-level checks need the resource, so they live in the handler or in a query filter.Location anywhere. The server must decide which destinations are legitimate.SqlException, file paths, type names). They belong in logs with a correlation id, not responses.| Class | Pattern |
|---|---|
| Injection | EF Core LINQ or FromSql interpolation; EF1002 as error; sort maps |
| BOLA | Tenant/customer global query filters, or loading through a repository that always scopes by caller; resource-based authorisation handlers |
| Open redirect | Only LocalRedirect in controllers; API endpoints never redirect |
| Error disclosure | AddProblemDetails + UseExceptionHandler; no local catch-all blocks |
Returning 403 confirms the id exists, letting attackers enumerate valid invoice numbers. Returning 404 for 'doesn't exist or isn't yours' leaks nothing. Log the attempt with the caller id, because repeated 404s across many ids are a signal.
WebApplicationFactory with a test auth handler): user A can't read or void user B's invoice; the response has no stack trace; returnUrl=//evil.example falls back to /.One-off fixes regress. The durable outcome of a review like this is a pattern (scoped queries), a guardrail (analysers, CI grep), and a test convention (authorisation test per id-taking endpoint).
The fixed controller: parameterised, allow-listed sorting with EF Core, caller-scoped loading (BOLA fix), no redirect from the API, and errors handled globally with ProblemDetails.
using System.Linq.Expressions;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Billing.Invoices;
public sealed record InvoiceSummary(int Id, string Number, string CustomerName, decimal Total, InvoiceStatus Status);
public interface ICurrentCustomer { int CustomerId { get; } }
public sealed class ClaimsCurrentCustomer(IHttpContextAccessor accessor) : ICurrentCustomer
{
public int CustomerId => int.Parse(accessor.HttpContext!.User.FindFirstValue("customer_id")
?? throw new UnauthorizedAccessException("No customer claim."));
}
[ApiController]
[Route("api/invoices")]
[Authorize]
public sealed class InvoicesController(BillingDb db, ICurrentCustomer caller) : ControllerBase
{
private static readonly Dictionary<string, Expression<Func<Invoice, object>>> SortFields =
new(StringComparer.OrdinalIgnoreCase)
{
["number"] = i => i.Number,
["total"] = i => i.Total,
["issued"] = i => i.IssuedUtc,
};
[HttpGet("search")]
public async Task<ActionResult<IReadOnlyList<InvoiceSummary>>> Search(
[FromQuery] string? customer, [FromQuery] string sort = "issued", CancellationToken ct = default)
{
if (!SortFields.TryGetValue(sort, out var orderBy))
return ValidationProblem($"Unsupported sort field '{sort}'.");
var query = db.Invoices.AsNoTracking()
.Where(i => i.CustomerId == caller.CustomerId); // scope first
if (!string.IsNullOrWhiteSpace(customer))
query = query.Where(i => EF.Functions.Like(i.CustomerName, $"%{customer}%")); // parameterised
var results = await query.OrderBy(orderBy)
.Take(100)
.Select(i => new InvoiceSummary(i.Id, i.Number, i.CustomerName, i.Total, i.Status))
.ToListAsync(ct);
return Ok(results);
}
[HttpPost("{id:int}/void")]
public async Task<IActionResult> Void(int id, CancellationToken ct)
{
// BOLA fix: only the caller's own invoices are visible; 404 avoids confirming the id exists
var invoice = await db.Invoices
.SingleOrDefaultAsync(i => i.Id == id && i.CustomerId == caller.CustomerId, ct);
if (invoice is null) return NotFound();
invoice.Void(); // domain rule: e.g. can't void a paid invoice
await db.SaveChangesAsync(ct);
return NoContent(); // the client decides where to navigate: no redirect from an API
}
}
// Program.cs: no local try/catch; one place turns exceptions into safe ProblemDetails
builder.Services.AddProblemDetails();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentCustomer, ClaimsCurrentCustomer>();
var app = builder.Build();
app.UseExceptionHandler(); // 500 + ProblemDetails with traceId; details only in logs
app.UseStatusCodePages();
// Integration test: user A cannot void user B's invoice
[Fact]
public async Task Void_other_customers_invoice_returns_404()
{
var client = factory.CreateClientFor(customerId: 1);
var response = await client.PostAsync("/api/invoices/2001/void", null); // invoice belongs to customer 2
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
customer. Why it is wrong: the sort identifier is still injectable and escaping is fragile. Instead: parameterise values and allow-list identifiers.[Authorize] on the controller covers Void. Why it is wrong: it checks authentication, not ownership of invoice id. Instead: scope the query or use resource-based authorisation.ex.ToString() with ex.Message. Why it is wrong: messages still leak SQL and internals (SqlException messages include object names). Instead: generic ProblemDetails with a trace id; details in logs.StartsWith("/") check. Why it is wrong: //evil.example passes. Instead: Url.IsLocalUrl + LocalRedirect, or remove redirects from APIs.A senior security review has two outputs: fixes for this PR and a guardrail for the codebase. The individual bugs are textbook; what distinguishes the review is ranking them, proving each with a test, and turning the lesson into something automatic so the next PR can't repeat it.
| Guardrail | When it fits | Cost | Limitation |
|---|---|---|---|
| Analysers as errors (EF1002, CA security rules) | Every repo | Initial clean-up | Doesn't catch logic flaws like BOLA |
| Tenant/customer global query filters | Multi-tenant data | Care with IgnoreQueryFilters and background jobs |
Not for cross-tenant admin queries |
| Authorisation test per id-taking endpoint | APIs with object ids | Test setup with a fake auth handler | Must be maintained |
| PR template security checklist | Teams of any size | Minutes per PR | Only as good as reviewers' attention |
| DAST in staging (ZAP) | Public apps and APIs | Pipeline time, triage | Misses authorisation logic |
Measure: security findings per pen test trending down, time from finding to fix, and the count of endpoints without an authorisation test.
Broken object-level authorisation (BOLA, also called IDOR) is API1:2023 in the OWASP API Security Top 10: the API checks who you are but not whether this object is yours.
callerId read from the token's claims, never from the request (Where(o => o.Id == id && o.CustomerId == callerId)), or load and call IAuthorizationService.AuthorizeAsync when roles or teams are involved; return 404, not 403.The trade-off: random ids slow attackers down, but they are not authorisation; only a server-side ownership check is.
SQL injection happens when untrusted input is concatenated into SQL text, so the database parses part of the data as code. The fix is parameterisation: the SQL text is fixed and values travel separately as typed parameters (SqlParameter in ADO.NET, an anonymous object in Dapper, LINQ or FromSql($"...") in EF Core).
In EF Core 7 and later, FromSql, ExecuteSql and SqlQuery<T> take a FormattableString and turn every interpolation hole into a DbParameter; they are the current names for the older FromSqlInterpolated/ExecuteSqlInterpolated. The trap is FromSqlRaw($"... {input}") or ExecuteSqlRaw: they take a plain string, so interpolation happens before EF sees it and it's concatenation. Things that can't be parameters (column names, sort direction) must come from an allow-list. Stored procedures aren't automatically safe if they build dynamic SQL. Add a least-privilege login so a bug can't drop tables.
An open redirect is an endpoint that redirects to a URL from the request (?returnUrl=...) without checking it, so a link on your trusted domain sends users to a phishing site, or an attacker chains it to leak OAuth codes or tokens. In ASP.NET Core use LocalRedirect (throws for non-local URLs) or Url.IsLocalUrl (rejects //evil and /\evil), and allow-list any external destinations.
Clickjacking loads your page in an invisible iframe on the attacker's site, so the user's click lands on your 'Delete' or 'Approve' button. Prevent framing with Content-Security-Policy: frame-ancestors 'none' (or 'self'), plus X-Frame-Options: DENY for older clients, set globally in middleware. Both bugs are cheap to fix and common in pen-test reports.
How to tell it (STAR)
**S:** At [company] a customer reported invoices voided that they'd never touched, and another could see invoice numbers that weren't theirs. **T:** I led the response: stop it, fix it, and work out the impact. **A:** The Void action loaded any invoice by id with no ownership check, and the search built SQL by concatenation. I hotfixed both to scope by the caller's customer and return 404, used the audit log and Application Insights to find every cross-customer action in [90] days, restored the invoices and worked with [the privacy officer] on the NDB assessment. Then I added a customer query filter, parameterised the search and wrote authorisation tests for every endpoint. **R:** The hole was closed in [hours], [number] affected invoices were restored, the tests caught [two] more endpoints with the same flaw, and the next pen test found no object-level authorisation issues.
Last updated 23 Nov 2026.