Role-based data redaction and access control in ASP.NET Core
Authorization decides who may call an endpoint. Role-based redaction decides what they get back. How to do both in ASP.NET Core, and where data still leaks.
By M. Adnan Saleem · · Updated · 8 min read
On a vehicle cybersecurity platform I secured sensitive security data with four-tier role-based access control, secure .NET API integrations, and data redaction pipelines filtered by caller tier. The idea underneath is simple and often skipped: deciding who may call an endpoint is only half of access control. The other half is deciding what each caller gets back. The tier demo below shows one record answered four ways.
Hiding a field in the UI is not security
If the API returns a field and the frontend chooses not to show it, the field is one browser tool away from anyone who is logged in. Whatever a user must not see has to be removed on the server, before the response is serialized.
Two questions, two mechanisms
- May this caller use this endpoint at all? That is authorization, and ASP.NET Core policies answer it.
- Which parts of the answer may this caller see? That is redaction, and it needs its own step.
Tiers as policies
Give each user a tier claim at sign-in and express every rule as a named policy. Controllers then state what they need, and the rule itself lives in one place:
// Program.cs: each policy names the lowest tier that passes
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Tier2", policy => policy.RequireClaim("tier", "2", "3", "4"));
options.AddPolicy("Tier3", policy => policy.RequireClaim("tier", "3", "4"));
options.AddPolicy("Tier4", policy => policy.RequireClaim("tier", "4"));
});Listing the allowed values works for four tiers and gets tedious beyond that. When the rule is really "this tier or higher", say so once with a requirement and a handler:
public record MinimumTierRequirement(int Tier) : IAuthorizationRequirement;
public class MinimumTierHandler : AuthorizationHandler<MinimumTierRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, MinimumTierRequirement requirement)
{
if (int.TryParse(context.User.FindFirst("tier")?.Value, out var tier) && tier >= requirement.Tier)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
// Program.cs
builder.Services.AddSingleton<IAuthorizationHandler, MinimumTierHandler>();
options.AddPolicy("Tier3", policy => policy.AddRequirements(new MinimumTierRequirement(3)));Deny by default
An endpoint that someone forgot to decorate should not be public. A fallback policy applies to every endpoint that has no rule of its own, so forgetting an attribute fails closed:
builder.Services.AddAuthorization(options =>
{
// Any endpoint without its own rule still requires a signed-in user
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});The few endpoints that really are public, such as sign-in and health checks, then say so explicitly with [AllowAnonymous], which is easy to find in review.
Where the tier comes from
The tier must come from something the server issued and can verify: a claim in a signed token or a server-side session. It must never be read from a request header, query string or body, because the caller controls those. A claim in a token also stays valid until the token expires, so a user who is moved down a tier keeps the old access until then. Keep access tokens short-lived, and for the most sensitive records look the tier up on the server for each request.
Resource-based authorization: rules that depend on the record
Tiers answer "how much may this person see?". Many systems also need "may this person see this particular record?": only findings from their own team, or only documents they own. An [Authorize] attribute cannot answer that, because it runs before the record is loaded. Load the record first, then ask the authorization service with the record in hand:
public record SameTeamRequirement : IAuthorizationRequirement;
public class SameTeamHandler : AuthorizationHandler<SameTeamRequirement, Finding>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
SameTeamRequirement requirement,
Finding finding)
{
if (context.User.FindFirst("team")?.Value == finding.TeamId.ToString())
context.Succeed(requirement);
return Task.CompletedTask;
}
}
// Program.cs
builder.Services.AddSingleton<IAuthorizationHandler, SameTeamHandler>();
options.AddPolicy("SameTeam", policy =>
policy.Requirements.Add(new SameTeamRequirement()));
// In the endpoint, after the record is loaded
var result = await _authorization.AuthorizeAsync(User, finding, "SameTeam");
if (!result.Succeeded) return NotFound();The rule still lives in a named policy and a handler, so it is tested and reviewed like the tier rules. Returning 404 follows the reasoning in the section on status codes below. For lists, the same rule belongs in the query's Where clause, or the list shows what the detail endpoint refuses.
One redaction step, used everywhere
The endpoint loads the full record and hands it to a single function that builds the response for the caller's tier:
[Authorize(Policy = "Tier2")]
[HttpGet("findings/{id}")]
public async Task<ActionResult<FindingDto>> Get(Guid id)
{
var finding = await _findings.Find(id);
if (finding is null) return NotFound();
var tier = int.Parse(User.FindFirstValue("tier")!);
return FindingRedactor.For(tier, finding);
}public static class FindingRedactor
{
public static FindingDto For(int tier, Finding f) => new()
{
Id = f.Id,
Title = f.Title,
Severity = f.Severity,
// Each sensitive field names the tier that may see it; everyone else gets null
AffectedComponent = tier >= 3 ? f.AffectedComponent : null,
ReproductionSteps = tier >= 4 ? f.ReproductionSteps : null,
};
}Three properties make this hold up over time. The domain object never leaves the server; only the response object does. Every sensitive field states its own rule, so a reviewer can read the whole policy in one file. And a new field is absent from the response until someone adds it to the redactor, which makes the default safe.
Redact lists inside the database query
Loading full records and redacting them in memory works for one record. For a list of thousands, it reads every sensitive column only to throw most of it away. Write the same rules as an expression instead, and Entity Framework Core turns them into part of the SQL:
public static class FindingRedactor
{
// The same rules as For(), as an expression a database query can use
public static Expression<Func<Finding, FindingDto>> ForTier(int tier) =>
f => new FindingDto
{
Id = f.Id,
Title = f.Title,
Severity = f.Severity,
AffectedComponent = tier >= 3 ? f.AffectedComponent : null,
ReproductionSteps = tier >= 4 ? f.ReproductionSteps : null,
};
}
// The list endpoint: EF Core builds the redaction into the SQL
var findings = await _db.Findings
.Where(f => f.ProjectId == projectId)
.Select(FindingRedactor.ForTier(tier))
.ToListAsync();The database never sends the values a caller may not read, and the detail endpoint can use the same expression with .Where(f => f.Id == id).Select(FindingRedactor.ForTier(tier)). Keep one copy of the rules: For can call ForTier(tier).Compile(), cached per tier, so the list, the detail page and the tests cannot drift apart.
Where data leaks anyway
- Lists and search. A redacted detail page is pointless if the list endpoint returns the full record. Send every response for that type through the same redactor.
- Exports and reports. CSV and PDF generation often bypasses the API layer. Give them the same step.
- Filters and counts. If a low tier can filter by a hidden field, the result count reveals it. Reject filters on fields the caller cannot read.
- Errors and logs. A validation message that quotes a hidden value leaks it. Keep sensitive values out of error text.
- Real-time channels. A WebSocket that broadcasts full records to every subscriber undoes all of the above. Redact per connection.
403, or 404?
The status code is part of what you reveal. If a low-tier caller asks for a record they may not see and gets 403 Forbidden, they have learned that the record exists. Where existence itself is sensitive, return 404 Not Found, exactly as for an id that was never issued. Use 403 when the caller may know the thing exists but may not perform the action.
Record who looked
For sensitive data, access control is not finished until reads are recorded: who requested which record, at which tier, and when. Log the identifiers, never the values, or the audit log becomes the easiest place to steal the data from.
Redact sensitive data in logs
Logging identifiers rather than values is the rule, and a library can enforce it for the values that slip through. Microsoft's Microsoft.Extensions.Compliance.Redaction lets you classify a log parameter as sensitive, and the logger redacts it before it is written:
// Packages: Microsoft.Extensions.Compliance.Redaction
// Microsoft.Extensions.Telemetry
public static class DataTaxonomy
{
public static DataClassification Sensitive => new("Security", nameof(Sensitive));
}
public sealed class SensitiveAttribute : DataClassificationAttribute
{
public SensitiveAttribute() : base(DataTaxonomy.Sensitive) { }
}
// Program.cs: the default redactor erases anything classified
builder.Logging.EnableRedaction();
builder.Services.AddRedaction();
public static partial class Log
{
[LoggerMessage(LogLevel.Warning,
"Export of finding {FindingId} failed for {ReporterEmail}")]
public static partial void ExportFailed(
this ILogger logger, Guid findingId, [Sensitive] string reporterEmail);
}With no redactor configured for a classification, the value is erased. An HMAC redactor can replace it with a keyed hash instead, which lets you correlate log lines about the same person without storing who they are; Microsoft still marks that one experimental.
Test it as a table
Access rules are a grid of tiers against fields, so test them as one: for every tier, request the same record and assert exactly which fields are present. When someone adds a field, the test for the lowest tier fails until they decide who may see it. That failing test is the review.
[Theory]
[InlineData(2, false, false)]
[InlineData(3, true, false)]
[InlineData(4, true, true)]
public void Each_tier_sees_only_its_fields(int tier, bool seesComponent, bool seesSteps)
{
var dto = FindingRedactor.For(tier, SampleFinding());
Assert.Equal(seesComponent, dto.AffectedComponent is not null);
Assert.Equal(seesSteps, dto.ReproductionSteps is not null);
}One row per tier, one column per sensitive field. The test reads like the policy document, which is the point: a security reviewer who does not write C# can still check it.
- 200
- OK
- 3
- fields sent
- 2
- fields withheld
{
"id": "F-2291",
"title": "Unsigned firmware accepted over diagnostics",
"severity": "High",
"affectedComponent": null,
"reproductionSteps": null
}An invented finding. The redaction runs in your browser here; in production it runs on the server, before the response is serialized.
Quick answers
The short version
What is the difference between authorization and redaction?
Authorization decides whether a caller may use an endpoint at all. Redaction decides which fields of the answer that caller receives.
Is hiding a field in the frontend enough?
No. If the API returns the field, anyone signed in can read it in the browser's network tab. It has to be removed on the server before the response is serialized.
Should a forbidden record return 403 or 404?
Return 404 when the caller is not allowed to know the record exists, and 403 when the existence is not a secret but the action is not allowed.
Where should redaction happen in ASP.NET Core?
In one step between the domain object and the response object, used by every endpoint, export and real-time channel that returns that type. For lists, write it as an expression so Entity Framework Core applies it inside the SQL query.
What is the difference between role-based and resource-based authorization?
Role-based authorization checks only the caller, so an [Authorize] attribute can decide it before any data is loaded. Resource-based authorization checks the caller against one record, such as its team or owner, so it runs in code after the record is loaded, through IAuthorizationService.
How do I redact sensitive data in ASP.NET Core logs?
Use Microsoft.Extensions.Compliance.Redaction with Microsoft.Extensions.Telemetry: call AddRedaction and EnableRedaction, then mark sensitive LoggerMessage parameters with a data classification attribute. The default redactor erases the value.
Keep reading
Related articles
- Stored procedures in Entity Framework Core: call, map, testWhen a stored procedure belongs in an EF Core app, how to call one with FromSql and ExecuteSql, read output parameters, map saves, and test the data layer.
- DDD and CQRS in a .NET module without the ceremonyDDD and CQRS in a Blazor Server and EF Core module: aggregates that guard the rules, one handler per command, queries as projections, no MediatR.
- Visual FoxPro forms to Blazor: events, buffering, validationMove a Visual FoxPro form to Blazor and EF Core: read the .scx as a table, move Valid rules into the domain, and replace table buffering with rowversion.
The project behind this
Read the case study
What I built, where, and the numbers that came out of it.
Related experience: .NET developer.