Blog

Use Subscrio to enforce paid feature access in a Blazor Web App

A Blazor page previews a paid export button while the server independently checks the customer's Subscrio feature and row limit.

Use Subscrio feature values in a Blazor app to show the right export option and limit the rows a customer can download. Then enforce those rules again in the endpoint. A hidden button changes the page, but it does not protect the URL behind it.

The example is a C#/.NET 10 feedback app. Its Studio plan allows CSV export up to a numeric row limit. ASP.NET Core authenticates the user, and the app resolves that user to a trusted Subscrio customer key. Subscrio supplies the customer’s feature values; the server checks them before it returns the file.

Create the server-interactive app

Create a server-interactive app with the .NET template, then install Subscrio.Core:

dotnet new blazor --framework net10.0 --interactivity Server -o FeedbackDesk
cd FeedbackDesk
dotnet add package Subscrio.Core --version 0.5.1
dotnet add package System.Security.Cryptography.Pkcs --version 9.0.21

Subscrio.Core 0.5.1 targets .NET 8 and runs on .NET 10. Its dependency graph resolved System.Security.Cryptography.Pkcs 9.0.11 in the build for this example. That version is affected by CVE-2026-70162; the patched 9.0.21 package is pinned above. Check your resolved packages during restore because transitive versions can change. Keep your app’s existing authentication scheme configured before you apply [Authorize] or .RequireAuthorization(). Subscrio does not replace identity or process payments.

Register Subscrio with the server app

Keep the library and its database connection in server-side code. The configuration below reads the connection string from the app’s ConnectionStrings:Subscrio configuration key. Supply it through your local user-secrets store and production secret manager, not a checked-in settings file.

using Subscrio.Core.Config;
using Subscrio.Core.DependencyInjection;
using Subscrio.Core.Domain.ValueObjects;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAuthorization();

var subscrioConnection = builder.Configuration.GetConnectionString("Subscrio")
    ?? throw new InvalidOperationException(
        "Set the ConnectionStrings:Subscrio secret before starting the app.");

builder.Services.AddSubscrio(new SubscrioConfig
{
    Database = new DatabaseConfig
    {
        ConnectionString = subscrioConnection,
        DatabaseType = DatabaseType.PostgreSQL
    }
});

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();
app.Run();

AddSubscrio registers the SDK as a scoped service by default, which fits a server-side web app. It does not install or migrate the schema. Set up the supported database and install the schema before the app handles requests. Keep installation in a one-time deployment or maintenance step, not in the app’s regular startup path.

Run this in a one-time setup command that can read the same database secret. After you upgrade Subscrio, call its migration method through your deployment process.

using Subscrio.Core.Config;
using Subscrio.Core.Domain.ValueObjects;

var connectionString = Environment.GetEnvironmentVariable("SUBSCRIO_CONNECTION_STRING")
    ?? throw new InvalidOperationException("Set SUBSCRIO_CONNECTION_STRING.");
var adminPassphrase = Environment.GetEnvironmentVariable("SUBSCRIO_ADMIN_PASSPHRASE")
    ?? throw new InvalidOperationException("Set SUBSCRIO_ADMIN_PASSPHRASE.");

var config = new SubscrioConfig
{
    Database = new DatabaseConfig
    {
        ConnectionString = connectionString,
        DatabaseType = DatabaseType.PostgreSQL
    }
};

using var subscrio = new Subscrio.Core.Subscrio(config);
if (await subscrio.VerifySchemaAsync() is null)
    await subscrio.InstallSchemaAsync(adminPassphrase);

Define the feature and plan values once

Create these catalog records from an administrative task. The toggle controls whether a customer can export at all; the numeric value caps each file.

using Subscrio.Core.Application.DTOs;
using SubscrioClient = Subscrio.Core.Subscrio;

public static class FeedbackDeskCatalog
{
    public static async Task SeedAsync(SubscrioClient subscrio)
    {
        if (await subscrio.Products.GetProductAsync("feedbackdesk") is null)
            await subscrio.Products.CreateProductAsync(
                new CreateProductDto("feedbackdesk", "FeedbackDesk"));

        if (await subscrio.Features.GetFeatureAsync("csv-export") is null)
            await subscrio.Features.CreateFeatureAsync(new CreateFeatureDto(
                "csv-export", "CSV export", "toggle", "false"));

        if (await subscrio.Features.GetFeatureAsync("max-export-rows") is null)
            await subscrio.Features.CreateFeatureAsync(new CreateFeatureDto(
                "max-export-rows", "Rows per CSV export", "numeric", "0"));

        await subscrio.Products.AssociateFeatureAsync(
            "feedbackdesk", "csv-export");
        await subscrio.Products.AssociateFeatureAsync(
            "feedbackdesk", "max-export-rows");

        await EnsurePlanAsync(subscrio, "feedbackdesk-free", "Free",
            csvExport: "false", maxRows: "0");
        await EnsurePlanAsync(subscrio, "feedbackdesk-studio", "Studio",
            csvExport: "true", maxRows: "2500");

        if (await subscrio.BillingCycles.GetBillingCycleAsync(
                "feedbackdesk-studio-monthly") is null)
            await subscrio.BillingCycles.CreateBillingCycleAsync(
                new CreateBillingCycleDto(
                    "feedbackdesk-studio", "feedbackdesk-studio-monthly",
                    "Studio monthly", "months", DurationValue: 1));

        if (await subscrio.BillingCycles.GetBillingCycleAsync(
                "feedbackdesk-free-ongoing") is null)
            await subscrio.BillingCycles.CreateBillingCycleAsync(
                new CreateBillingCycleDto(
                    "feedbackdesk-free", "feedbackdesk-free-ongoing",
                    "Free ongoing", "forever"));

        foreach (var customerKey in new[] { "studio-demo", "free-demo" })
            if (await subscrio.Customers.GetCustomerAsync(customerKey) is null)
                await subscrio.Customers.CreateCustomerAsync(
                    new CreateCustomerDto(customerKey, customerKey));

        foreach (var (subscriptionKey, customerKey, cycleKey) in new[]
        {
            ("studio-demo-subscription", "studio-demo", "feedbackdesk-studio-monthly"),
            ("free-demo-subscription", "free-demo", "feedbackdesk-free-ongoing")
        })
            if (await subscrio.Subscriptions.GetSubscriptionAsync(subscriptionKey) is null)
                await subscrio.Subscriptions.CreateSubscriptionAsync(
                    new CreateSubscriptionDto(subscriptionKey, customerKey, cycleKey));
    }

    private static async Task EnsurePlanAsync(
        SubscrioClient subscrio, string key, string name,
        string csvExport, string maxRows)
    {
        if (await subscrio.Plans.GetPlanAsync(key) is null)
            await subscrio.Plans.CreatePlanAsync(
                new CreatePlanDto("feedbackdesk", key, name));

        await subscrio.Plans.SetFeatureValueAsync(key, "csv-export", csvExport);
        await subscrio.Plans.SetFeatureValueAsync(key, "max-export-rows", maxRows);
    }
}

CreateFeatureDto gives each feature a stable key and a value type. The code sets csv-export and max-export-rows on the Free and Studio plans. It also creates sample customers and subscriptions so you can inspect the two configured cases in a development environment. The monthly cycle has no external price and does not take payment. Keep these seed records out of a production billing flow.

Your billing integration updates the customer’s Subscrio subscription after it verifies a payment event. Resolve the customer and plan from trusted server-side records. Never accept a customer key or plan key from a browser request.

Resolve the customer in the authenticated server context

The endpoint reads a claim named subscrio_customer_key. Your authentication and tenant code must add it only after checking the user’s account and membership on the server. A browser must never set this value. If users can switch organizations, resolve the selected organization through a server-side membership check for each request instead of keeping one organization in a user-level claim.

The export route checks authentication, the feature, and the row allowance before it queries or creates the file:

Use the app’s existing EF Core context to make the export query concrete. The example filters by customer key before it applies the plan’s row limit.

using Microsoft.EntityFrameworkCore;

public sealed class FeedbackDeskDbContext(
    DbContextOptions<FeedbackDeskDbContext> options) : DbContext(options)
{
    public DbSet<FeedbackItem> Feedback => Set<FeedbackItem>();
}

public sealed class FeedbackItem
{
    public int Id { get; set; }
    public required string CustomerKey { get; set; }
    public required string Title { get; set; }
    public int Votes { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
}

Register that context with the same provider and connection your application already uses. The example intentionally leaves your application schema and database provisioning out of this feature-access walkthrough.

using System.Security.Claims;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using SubscrioClient = Subscrio.Core.Subscrio;

app.MapGet("/api/reports/export", async (
    ClaimsPrincipal user,
    SubscrioClient subscrio,
    FeedbackDeskDbContext db,
    CancellationToken cancellationToken) =>
{
    var customerKey = user.FindFirst("subscrio_customer_key")?.Value;
    if (user.Identity?.IsAuthenticated != true ||
        string.IsNullOrWhiteSpace(customerKey))
        return Results.Forbid();

    var canExport = await subscrio.FeatureChecker.IsEnabledForCustomerAsync(
        customerKey, "feedbackdesk", "csv-export");
    if (!canExport)
        return Results.Forbid();

    var rowLimit = await subscrio.FeatureChecker.GetValueForCustomerAsync<int>(
        customerKey, "feedbackdesk", "max-export-rows", 0);
    if (rowLimit < 1)
        return Results.Forbid();

    var rows = await db.Feedback
        .AsNoTracking()
        .Where(item => item.CustomerKey == customerKey)
        .OrderByDescending(item => item.CreatedAt)
        .Take(rowLimit)
        .Select(item => new { item.Title, item.Votes })
        .ToListAsync(cancellationToken);

    var csv = new StringBuilder("title,votes\r\n");
    foreach (var row in rows)
        csv.Append(Escape(row.Title)).Append(',').Append(row.Votes).Append("\r\n");

    return Results.File(
        Encoding.UTF8.GetBytes(csv.ToString()),
        "text/csv; charset=utf-8",
        "feedback.csv");
})
.RequireAuthorization();

static string Escape(string value) =>
    "\"" + value.Replace("\"", "\"\"") + "\"";

Register FeedbackDeskDbContext with your app’s existing database provider. The query uses the authenticated customer’s server-resolved key and applies Take(rowLimit) in the database, so a request cannot raise its own allowance. The endpoint checks Subscrio even though the page also checks it; users can call the URL directly.

The route’s authorization middleware handles the sign-in boundary. For an authenticated customer without export access or a positive row limit, Results.Forbid() returns HTTP 403 without building a CSV. Your API can return a structured error or direct a user to an upgrade flow, but the server must still enforce the feature.

Show the same decision in the Blazor page

The page can query Subscrio to decide whether to render the link. The .NET 10 template uses RouteView; replace it with AuthorizeRouteView so the page’s [Authorize] attribute is enforced:

@using Microsoft.AspNetCore.Components.Authorization

<Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)">
            <NotAuthorized>
                <p>Sign in to view reports.</p>
            </NotAuthorized>
        </AuthorizeRouteView>
        <FocusOnNavigate RouteData="routeData" Selector="h1" />
    </Found>
</Router>

With AuthorizeRouteView, a signed-out visitor cannot render the protected report page. For a signed-in user, the component asks Subscrio about the customer resolved by the server. The endpoint keeps its own check because hiding the link is not access control.

@page "/reports"
@attribute [Authorize]
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject Subscrio.Core.Subscrio Subscrio

<PageTitle>Reports</PageTitle>
<h1>Reports</h1>

@if (!_loaded)
{
    <p>Checking report access...</p>
}
else if (_canExport)
{
    <a href="/api/reports/export">Download CSV</a>
}
else
{
    <p>CSV export is available on the Studio plan.</p>
}

@code {
    private bool _loaded;
    private bool _canExport;

    protected override async Task OnInitializedAsync()
    {
        var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = state.User;
        var customerKey = user.FindFirst("subscrio_customer_key")?.Value;

        if (user.Identity?.IsAuthenticated == true &&
            !string.IsNullOrWhiteSpace(customerKey))
        {
            _canExport = await Subscrio.FeatureChecker.IsEnabledForCustomerAsync(
                customerKey, "feedbackdesk", "csv-export");
        }

        _loaded = true;
    }
}

Interactive Server runs this component on the server. The scoped Subscrio client checks the feature for the customer mapped by the authentication system. The link appears only when export is allowed. A user can still copy a URL, so the endpoint checks authentication, feature access and the row limit before it reads the data.

Grant a customer-specific exception

When support or an administrator approves a temporary higher export allowance, add an override to that customer’s subscription from a trusted server-side administrative action:

using Subscrio.Core.Domain.ValueObjects;

await subscrio.Subscriptions.AddFeatureOverrideAsync(
    subscriptionKey: "studio-demo-subscription",
    featureKey: "max-export-rows",
    value: "5000",
    overrideType: OverrideType.Timed,
    expiresAt: DateTime.UtcNow.AddDays(14));

Use the subscription key from your server’s verified billing-to-customer mapping. This timed override raises the limit for one subscription and expires after 14 days. It leaves the shared Studio plan unchanged. Restrict this operation to trusted support or admin code and record the reason for the exception.

Keep each decision in its own layer

Authentication identifies the user, your app resolves the customer’s data, and Subscrio supplies the customer’s current feature values. The endpoint uses all three before it returns the CSV. Your billing integration remains responsible for updating Subscrio after payment changes.

Microsoft’s Blazor guidance warns that AuthorizeView controls what appears on screen but does not secure an event handler or server resource. Keep the page check for a clear interface, and enforce feature access at every server operation. This article uses C# throughout because its app and SDK are .NET.

Sources

Written by

Jasen Fici

Founder, Subscrio

Bootstrapped founder. Built Velaro and StatusCast. Now building Subscrio, an entitlement engine for software products.

Screenshot preview