How to Implement Secure File Downloads in ASP.NET Core 10 Using Signed URLs and Expiring Tokens (2026)

An ASP.NET Core secure file download can use an HMAC-signed URL that expires and is bound to the authenticated user. Check access when issuing the link and again when serving the file. Keep files outside wwwroot so the download endpoint controls who gets the bytes.

What does a signed download URL protect?

Authorize link issuance. Sign file ID and expiration. Verify signature and caller. Serve the permitted file range.
Authorize link issuance. Sign file ID and expiration. Verify signature and caller. Serve the permitted file range.

The sample signs the numeric file ID, expiration, and authenticated subject. A caller can see and change the query string, but cannot generate a valid replacement signature without the key. The authenticated subject also has to own the file. This makes a forwarded URL unusable by a different account.

Check Purpose
Authentication Establish the caller identity
Ownership Verify the caller can access this file now
Expiration Limit the lifetime of the signed request
HMAC Detect changes to the signed values
Private storage Ensure a second URL cannot bypass checks

The signature input includes a purpose prefix and culture-invariant serialization. Keep this format stable across replicas. If you add new fields, document the encoding and start a new format version. Use a different signing key or purpose for other application features.

Implement link issuance and range downloads

Create a .NET 10 web project with the JWT bearer package below. Use a trusted issuer in deployed systems. For the lab, create a Development token with a subject of alice. Set Download__Key to a base64-encoded random value containing at least 32 bytes. For example, use openssl rand -base64 32 and keep its output in local secrets. Create private-files/sample-report.txt under the project content root and put harmless text in it.

Sample.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.*" />
  </ItemGroup>
</Project>
Program.cs
using System.Globalization;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.WebUtilities;

var b = WebApplication.CreateBuilder(args);
b.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
b.Services.AddAuthorization();
var app = b.Build();
var key = Convert.FromBase64String(b.Configuration["Download:Key"]
    ?? throw new InvalidOperationException("Set Download__Key to a Base64 secret."));
if (key.Length < 32) throw new InvalidOperationException("Use at least 32 random bytes.");

var root = Path.Combine(app.Environment.ContentRootPath, "private-files");
var files = new Dictionary<int, (string Subject, string Name)>
{
    [1] = ("alice", "sample-report.txt")
};

app.MapPost("/download-links/{id:int}", (int id, ClaimsPrincipal user, HttpContext http) =>
{
    http.Response.Headers.CacheControl = "private, no-store";
    var sub = Subject(user);
    if (sub is null || !files.TryGetValue(id, out var file) || file.Subject != sub)
        return Results.NotFound();

    var exp = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds();
    var sig = WebEncoders.Base64UrlEncode(Sign(key, id, sub, exp));
    return Results.Ok(new { url = $"/downloads/{id}?exp={exp.ToString(CultureInfo.InvariantCulture)}&sig={sig}" });
}).RequireAuthorization();

app.MapGet("/downloads/{id:int}", (int id, long exp, string sig, ClaimsPrincipal user,
    HttpContext http, ILogger<Program> log) =>
{
    http.Response.Headers.CacheControl = "private, no-store";
    http.Response.Headers["Referrer-Policy"] = "no-referrer";
    var sub = Subject(user);
    if (sub is null || !files.TryGetValue(id, out var file) || file.Subject != sub)
        return Results.NotFound();

    if (exp <= DateTimeOffset.UtcNow.ToUnixTimeSeconds() || sig.Length != 43)
        return Results.StatusCode(403);
    byte[] provided;
    try { provided = WebEncoders.Base64UrlDecode(sig); }
    catch (FormatException) { return Results.StatusCode(403); }

    if (!CryptographicOperations.FixedTimeEquals(provided, Sign(key, id, sub, exp)))
        return Results.StatusCode(403);

    var path = Path.Combine(root, file.Name);
    if (!File.Exists(path)) return Results.NotFound();
    log.LogInformation("Authorized download for FileId {FileId}", id);
    return Results.File(path, "application/octet-stream", file.Name, enableRangeProcessing: true);
}).RequireAuthorization();
app.Run();

static string? Subject(ClaimsPrincipal user) =>
    user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub");

static byte[] Sign(byte[] key, int id, string subject, long expiration)
{
    var input = FormattableString.Invariant(
        $"download-v1\n{id}\n{expiration}\n{subject.Length}\n{subject}");
    return HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(input));
}

The static dictionary is the sample’s file catalog. In a real system, retrieve the owner and storage identifier from a trusted database. Use a storage root the application can read and external callers cannot modify. Prevent symlinks or reparse points from crossing that root where they are possible. Accepting a caller’s raw filesystem path in the download route introduces a different security problem.

The file result serves bytes without loading the entire file into an application buffer. Range support allows resumable downloads when a client requests it. Authorize every range request. Stable file contents matter while clients resume. If the object can change, sign an immutable storage version or validate the version at download time.

Test success and rejection paths

Run the app with Development JWT configuration on http://localhost:5091. Use the ASP.NET Core developer JWT tool to generate the token for the sample and verify its subject before continuing. The example assumes TOKEN contains an Alice bearer token and jq is installed.

BASH
url=$(curl --fail -sS -X POST -H "Authorization: Bearer $TOKEN" \
  http://localhost:5091/download-links/1 | jq -r .url)
curl -i -H "Authorization: Bearer $TOKEN" -H 'Range: bytes=0-3' \
  "http://localhost:5091$url"

For a sample file of at least four bytes, expect 206 with Content-Range and four bytes. Omit Range and expect 200. Remove Authorization and expect 401. Request the signed URL as a different account and expect 404. Change the expiration or the signature and expect 403 with a valid Alice token. Wait more than five minutes and repeat to test expiration. Quote the URL so the shell preserves the ampersand.

Operational and security considerations

This lab requires a bearer header on the download request. An ordinary browser link does not attach an application bearer token by itself. Use an authenticated fetch or adapt the endpoint to a secure same-origin cookie. Use antiforgery protection on link issuance when it accepts cookie authentication.

Use HTTPS in deployment. Redact the signature and query string from CDN, reverse proxy and application logs. Audit object IDs and outcomes with minimal necessary identity data. Store the signing key in an appropriate secret store. Plan rotation by including a key identifier in the signed input and retaining a previous key for a bounded overlap. Align expiration with large-file retries and download clients.

A five-minute signature can be reused by its owner during that window. Immediate revocation needs a server-side policy, ownership check or revocation record. A single-use link needs shared atomic state, and can conflict with ranged downloads or aggressive retry behavior. Decide whether consumption is per download session or per request.

Troubleshooting and FAQ

Symptom Check
Works in curl but not in a browser Confirm the browser sent the required credential
Intermittent 403 across replicas Compare signing keys, clock skew and signed-input formatting
Range returns the wrong data after a retry Check file version, Content-Range, and proxy behavior
File exists but returns 404 Check the catalog, subject and application content root

Are signed URLs encrypted? HMAC provides integrity. Query parameters are still visible to the client and to systems that log the URL.

Can I use this with cloud object storage? Yes. Compare serving through the app with issuing a provider-specific signed URL. The provider’s access and revocation model determines how a forwarded link behaves.

See HMACSHA256.HashData and Results.File. Related guides include JWT authentication and deploying to IIS.

Comments