Scope inventory by warehouse with Azure SQL Database
Deploy the ShopStream inventory sample to App Service Builder. You'll connect it to Azure SQL Database without storing a database password, then verify that two signed-in users see only their assigned warehouses.
Builder serves the React catalog and inventory UI at / and Data API builder (DAB) on .NET 10 at /api on the same origin.
Node.js 24 builds the UI and runs the database setup scripts; it doesn't serve the API.
Builder authenticates visitors with Microsoft Entra ID.
DAB connects to SQL as the app's managed identity and passes each verified visitor's tenant and object IDs into SQL session context.
SQL row-level security (RLS) uses that context to filter inventory.
Use synthetic data and a dedicated test database. Confirm that your Builder target supports the sample's runtimes, required sign-in, managed identity, and Azure SQL connection. Before provisioning, review costs and confirm that your organization permits the SQL network access described below.
Prerequisites
- An Azure subscription with App Service Builder access in West US 2 (
westus2) and permission to create a test SQL server, set its Microsoft Entra administrator, and configure the Builder app. - Git, curl, Node.js 24/npm, Azure CLI with Bicep, and a SQL client that supports Entra authentication.
- A GitHub fork with the Builder GitHub App authorized before provisioning, including for public forks (GitHub authorization).
- Your tenant ID and the object IDs of two distinct test users: an initial warehouse manager and a viewer in the same tenant.
1. Prepare the source and database
Clone the sample
Fork the Azure SQL sample. If you already have a fork, sync it from the sample before cloning. Clone your fork and create a branch at the revision used in this tutorial:
git clone "<your-fork-https-url>" shopstream-sql
cd shopstream-sql
git switch -c azure-sql-tutorial d5046ec9620247cc5c40abf9cde1f8419eb2b69e
Keep the root builder.yaml: it builds the UI from dab/ui and the API from dab.
Provision Azure SQL
The sample's template creates an Entra-only General Purpose serverless database with 0.5–2 vCores and a 60-minute auto-pause. Compute, storage, and backups can incur charges; connections or requests can wake the database, and a resume can exceed an HTTP timeout. The template permits only the workstation IPv4 you specify; it doesn't enable Builder access.
In a dedicated Bash terminal, use your own IDs, a new test resource group, and an approved workstation public IPv4 address. The SQL administrator must be an Entra user, not the app identity.
export AZURE_SUBSCRIPTION_ID="<subscription-id>"
export AZURE_TENANT_ID="<tenant-id>"
export RG="<new-test-resource-group>"
export SQL_SERVER_NAME="<globally-unique-sql-server-name>"
export ADMIN_OBJECT_ID="<sql-admin-user-object-id>"
export ADMIN_NAME="<sql-admin-user-principal-name>"
export ADMIN_IP="<approved-workstation-public-ipv4>"
export MANAGER_OBJECT_ID="<manager-user-object-id>"
export VIEWER_OBJECT_ID="<viewer-user-object-id>"
az login --tenant "$AZURE_TENANT_ID"
az account set --subscription "$AZURE_SUBSCRIPTION_ID"
az group create --subscription "$AZURE_SUBSCRIPTION_ID" \
--name "$RG" --location westus2
SQL_PARAMS=(
serverName="$SQL_SERVER_NAME" administratorObjectId="$ADMIN_OBJECT_ID"
administratorName="$ADMIN_NAME" allowedClientIpAddresses="[\"$ADMIN_IP\"]"
)
az deployment group what-if --subscription "$AZURE_SUBSCRIPTION_ID" \
--resource-group "$RG" --name asb-sql-dependency \
--template-file infra/main.bicep --parameters "${SQL_PARAMS[@]}"
Review the proposed resources and costs before creating them:
az deployment group create --subscription "$AZURE_SUBSCRIPTION_ID" \
--resource-group "$RG" --name asb-sql-dependency \
--template-file infra/main.bicep --parameters "${SQL_PARAMS[@]}"
Initialize the database
Sign in above as the SQL administrator. Use a clean terminal environment so default credentials don't select an unrelated service principal. The catalog bootstrap requires a new, empty database with compatibility level 160 or later. It creates and seeds the catalog without granting runtime permissions; rerunning a completed bootstrap doesn't reseed it. Run it before the inventory migration:
export SQL_SERVER="$SQL_SERVER_NAME.database.windows.net"
export SQL_DATABASE=shopstream
export ENTRA_CREDENTIAL=default
export INVENTORY_CONFIRM_DATABASE="$SQL_DATABASE"
export INVENTORY_TENANT_ID="$AZURE_TENANT_ID"
export INVENTORY_MANAGER_OBJECT_ID="$MANAGER_OBJECT_ID"
unset SQL_CONNECTION_STRING SQL_USER SQL_PASSWORD DATABASE_URL SQL_PORT AZURE_CLIENT_ID
npm ci
node db/catalog/setup.js bootstrap
node db/inventory/setup.js migrate
The migration adds inventory row-level security (RLS), copies stock into Seattle and Austin demo warehouses, and makes the initial user a manager of both. Rerunning it doesn't reseed inventory.
Prepare a read-only deployment
DAB loads procedure metadata at startup, so a fresh app can time out if it deploys InventoryCommand before the write grant exists.
Remove that entity first and push the change to your fork:
node <<'NODE'
const fs = require('node:fs');
const path = 'dab/dab-config.json';
const config = JSON.parse(fs.readFileSync(path, 'utf8'));
if (!config.entities?.InventoryCommand) throw new Error('InventoryCommand not found');
delete config.entities.InventoryCommand;
fs.writeFileSync(path, JSON.stringify(config, null, 2) + '\n');
NODE
git add dab/dab-config.json
git commit -m "Start inventory in read-only mode"
git push origin HEAD
2. Require Entra sign-in before creating the app
Use the Portal creation flow with Use my repository, your fork, the branch you just pushed, and root builder.yaml.
Set authentication in the wizard: Create and deploy starts the first deployment immediately.
- In Authentication, select Required and turn on Microsoft Entra ID. Keep the managed application and leave GitHub sign-in off.
- Turn on Limit to specific identities. Under Tenant IDs, add your tenant; under Object IDs, add both tester IDs. A tenant rule alone admits everyone in that tenant.
- In App details, choose your subscription, test resource group, and West US 2. In Review, confirm Sign-in reads Required with Microsoft Entra ID, then select Create and deploy.
- On the app's Authentication page, confirm the policy and select Test sign-in. The initial deployment can't read SQL yet; keep the app and finish setup.

The tenant and user IDs shown are placeholders; enter your own.
3. Connect the app to Azure SQL
- On Identity, turn on the system-assigned identity and select Save only to defer deployment.
Wait for the assignment to finish before configuring the connection.
Record its Object (principal) ID.
SQL needs the identity's client ID, not that principal ID.
An account with directory read access can find it with
az ad sp show --id "<app-identity-principal-id>" --query appId -o tsv. - On Architecture, select Add connection and choose Azure SQL.
Name the connection
database, select the existing SQL logical server and the app's system-assigned identity, and set the target database name. Keep the generatedSQL_CONNECTION_STRINGmapping and verified TLS (Encrypt=True;TrustServerCertificate=False). Don't add a duplicate variable, password, or token. - On Variables, set
ASPNETCORE_URLStohttp://0.0.0.0:8080andWEBSITE_AUTH_ENABLEDtotrue, then select Save only. Set the latter only after confirming required sign-in: it satisfies DAB's production-mode check but doesn't enable authentication.
DAB trusts the principal headers Builder verifies and replaces.
Don't expose DAB directly or trust client-supplied identity headers; keep the sample's closed CORS policy and X-Inventory-Command: 1 requirement for writes.
Saving a connection doesn't grant SQL permissions or deploy the settings.
Configure network access
Builder has no stable outbound IP or VNet/private endpoint connectivity. The workstation rule doesn't provide Builder access. The Allow Azure services and resources to access this server rule admits Azure-origin traffic across subscriptions and tenants; it isn't scoped to your app or suitable as production isolation.
Only with explicit approval for this scope on the dedicated test server, run:
az sql server firewall-rule create --subscription "$AZURE_SUBSCRIPTION_ID" \
--resource-group "$RG" --server "$SQL_SERVER_NAME" \
--name AllowAllWindowsAzureIps --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0
If that access isn't approved, stop rather than weakening TLS or enabling SQL passwords.
4. Grant database access and deploy
Connect to the shopstream database as the Entra SQL administrator in your SQL client.
Replace the placeholder with the app identity's client ID and create a separate contained user for this app:
DECLARE @clientId uniqueidentifier = '<app-identity-client-id>';
DECLARE @sid varchar(34) = CONVERT(varchar(34), CONVERT(binary(16), @clientId), 1);
EXEC (N'CREATE USER [shopstream_dab_reader] WITH SID = ' + @sid + N', TYPE = E;');
GRANT SELECT ON OBJECT::dbo.products TO [shopstream_dab_reader];
GRANT SELECT ON OBJECT::dbo.categories TO [shopstream_dab_reader];
In the same Bash terminal used for initialization, grant the six inventory read views:
export RUNTIME_ROLE=shopstream_dab_reader
export RUNTIME_CLIENT_ID="<app-identity-client-id>"
node db/inventory/setup.js grant-read
Don't reuse another app's SQL user or grant db_owner, db_datawriter, or direct inventory table writes.
Deploy the pushed read-only source with the saved connection and variables, then wait for the deployment to succeed.
5. Verify warehouse access
-
Copy the app URL from Overview and check an anonymous request:
export APP_URL="<your-app-https-url-without-trailing-slash>"
curl -s -o /dev/null -w '%{http_code}\n' "$APP_URL/api/products"Expect
401. Open the app in a private browser window and sign in as the manager. -
Check
/.auth/mefor the account and/api/accessfor the expected tenant and object IDs./api/productsshould return catalog rows, and/api/warehousesshould list Seattle and Austin. Note the Seattle warehouseidin that response. -
Select Open inventory. The Warehouse selector, Your SQL role: manager, and balances should appear.
The UI can still show manager operation controls; don't submit them until you've enabled writes below.

This hosted example uses synthetic data; your balances can differ.
Give the viewer access to one warehouse
Each tester needs both a Builder Entra allowlist entry and a SQL membership.
Visitors don't need individual SQL users.
As the SQL administrator, run this once in shopstream, replacing the placeholders with the Seattle ID from /api/warehouses and the viewer's tenant and object IDs:
DECLARE @warehouse_id int = <seattle-warehouse-id>;
DECLARE @tenant_id uniqueidentifier = '<tenant-id>';
DECLARE @object_id uniqueidentifier = '<viewer-object-id>';
INSERT inventory.warehouse_members (warehouse_id, tenant_id, actor_id, role)
VALUES (@warehouse_id, @tenant_id, @object_id, 'viewer');
Sign in as the viewer in a separate browser profile.
/api/warehouses and the Warehouse selector should show Seattle only; the role is viewer.
If No warehouse assigned appears, check the membership's exact tenant and object IDs.
RLS scopes warehouse reads, balances, reservations, and movements; receipts are also scoped to their submitting actor. The shared catalog isn't warehouse-scoped. RLS relies on trusted ingress and runtime, and doesn't protect against arbitrary SQL execution as the app identity or an administrator changing policies. Builder's default probe checks DAB reachability, not SQL access. If data doesn't load, check sign-in, connection mapping, grants, and network access.
Optional: Enable and verify inventory commands
For a disposable test database, run this in the same administrator terminal with RUNTIME_ROLE and RUNTIME_CLIENT_ID still set:
node db/inventory/setup.js grant-write
This grants EXECUTE on inventory.execute_command, not direct table writes.
Restore the InventoryCommand entity from the original sample in your fork, commit and push it, then deploy again.
A viewer can read; an operator can also receive, reserve, and release; a manager can additionally adjust stock.
As a manager, receive a small quantity and verify the applied receipt, updated balance, and movement after refreshing.
Confirm the viewer and an unassigned warehouse can't change stock.
The procedure checks the caller's warehouse role independently of the UI.
An HTTP success doesn't prove the command applied: check the receipt's outcome.
If a request times out, reconcile the original request rather than issuing a new ID.
To disable commands, revoke EXECUTE on the procedure and redeploy without InventoryCommand.
Running grant-read again doesn't revoke earlier grants.
Clean up resources
Delete only the test app you created when you no longer need it. App deletion does not remove your GitHub repository, resource group, or separately owned services and user-assigned identities.
On updated targets, deletion first reports that it was accepted and then continues in the background.
In the Portal, keep the Deleting app's progress available until it completes.
With the updated Builder CLI, deletion waits by default; --no-wait returns an operation URL that you can inspect with builder app status.
Closing the client does not cancel an accepted deletion.
Recently published apps can wait for the remaining one-hour upload grant plus a two-minute drain, and provider failures can extend the wait.
The same app name in the same subscription and resource group stays unavailable until deletion finishes.
Full artifact cleanup remains under construction; existing lifecycles retain their earlier cleanup scope.
Return to the app inventory and choose Delete from the test app's actions. Alternatively, open the app's Settings and select Delete under Danger zone. Enter the exact app name and choose Delete. The dialog closes when the service accepts the request, without waiting for cleanup to finish. The app remains visible as Deleting, with changes disabled while cleanup runs. Deleting from Settings keeps the app open so you can follow its deletion progress.
A notification names the app and reports progress, then success or failure. You can open another app without losing deletion progress. Use the bell beside Docs and All activity to review it. If the request is rejected, the dialog shows the error and lets you retry. Deletion progress includes the current cleanup step and retry details when available. Wait for deletion to complete before creating another app with the same name. Refreshing or closing the Portal clears this session's tracking; it does not cancel server-side cleanup.
Deleting the Builder app doesn't delete the Azure SQL database or remove its firewall rules and contained user. Remove the Azure-services exception and any test workstation rules you created. If you keep the database, have its administrator remove the retired app's contained user and the sample-only warehouse memberships. For a live app, revoke a tester's access at both layers: remove the Entra allowlist entry and the SQL membership.
If you provisioned a dedicated database only for this tutorial, delete it in Azure after confirming ownership and accepting permanent data loss. Delete the logical server only if it hosts no other databases you need. Don't delete a shared resource group.
Related content
- Store application data in Azure PostgreSQL for a separate Node.js and PostgreSQL managed-identity sample.
- Deployed-app authentication and managed identity.
- App + Azure SQL sample for the DAB app and setup guide, administrator commands, local checks, and API details.