快速入门:将 SQL 行级别安全性与数据 API 生成器配合使用

在本快速入门中,你将使用 快速入门 5:行级安全示例 在 SQL Server 中实现按用户的数据隔离。 Web 应用使用 Microsoft Entra ID登录用户,向数据 API 生成器(DAB)发送持有者令牌,SQL 行级别安全性 (RLS) 会筛选数据库层上的行。

此示例在单页应用程序(SPA)中使用 Microsoft 身份验证库(MSAL)、DAB authenticated 角色,以及配合谓词函数和安全策略的 SQL Server 行级安全性(RLS)。 DAB 将经过身份验证的用户 preferred_username 声明映射到 SQL,SQL SESSION_CONTEXT会筛选该会话上下文中的行。 此示例不使用 DAB 的按实体划分的数据库策略,也不使用自定义 API 代码。

先决条件

示例显示的内容

  • 使用 MSAL 浏览器登录和自动重定向的静态 Web 应用。
  • 用于 Web 应用程序的 SPA 应用注册项,以及用于 DAB 的 API 应用注册项。
  • 浏览器请求 DAB 调用的委托 API 范围。
  • 从 Web 应用到 DAB 的持有者令牌调用。
  • DAB 配置为使用 Microsoft Entra ID EntraId 身份验证提供程序。
  • 使用 authenticated 角色的 DAB 实体权限。
  • 按已登录的用户的 preferred_username 声明筛选行的 SQL Server RLS。
  • 将 JSON Web 令牌 (JWT) 声明映射到 SQL SESSION_CONTEXT 的 DAB 会话上下文。
  • 从 DAB 到本地SQL Server开发容器的 SQL 身份验证。
  • DAB 通过系统分配的托管标识无密码访问 Azure SQL。
  • 在没有 DAB 按实体数据库策略的情况下,在 SQL 中按用户进行数据筛选。

身份验证流程

本地身份验证 Azure身份验证
从用户到 Web 应用 启用自动重定向的 Microsoft Entra ID 启用自动重定向的 Microsoft Entra ID
Web 应用到 API 持有者令牌 持有者令牌
API 角色 authenticated authenticated
API 转 SQL 使用 SQL RLS 进行 SQL 身份验证 使用 SQL RLS 系统分配的托管标识

与该系列比较

Step 哪些更改
上一个 将 DAB 策略用于按用户划分的数据 使用策略表达式筛选 DAB 中的行。
本快速入门 使用 DAB 填充的会话上下文将每用户筛选移动到 SQL RLS 中。
下一步 使用代表身份验证允许Azure SQL对实际登录用户进行身份验证。

RLS 策略

SQL Server使用谓词函数和安全策略强制实施行级别访问。

CREATE FUNCTION dbo.UserFilterPredicate(@OwnerId sysname)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN SELECT 1 AS IsVisible
WHERE @OwnerId = CAST(SESSION_CONTEXT(N'preferred_username') AS sysname);

CREATE SECURITY POLICY UserFilterPolicy
ADD FILTER PREDICATE dbo.UserFilterPredicate(Owner) ON dbo.Todos
WITH (STATE = ON);

data-source.options.set-session-contexttrue 时,DAB 会将已验证的 JWT 声明发送到 SQL 会话上下文。

{
  "data-source": {
    "database-type": "mssql",
    "connection-string": "@env('MSSQL_CONNECTION_STRING')",
    "options": {
      "set-session-context": true
    }
  }
}

数据库仅返回 Owner 列与 SESSION_CONTEXT(N'preferred_username') 匹配的行。 DAB 可以正常请求行;SQL 强制实施最终筛选器。

Important

此示例不使用 DAB 数据库策略,例如 @item.Owner eq @claims.preferred_username。 SQL RLS 拥有行筛选器。

使用样本

克隆示例存储库。

git clone https://github.com/Azure-Samples/dab-2.0-quickstart-web_entra-api_entra-db_entra-db_rls.git
cd dab-2.0-quickstart-web_entra-api_entra-db_entra-db_rls

恢复本地工具。

dotnet tool restore

登录到Azure。

az login

在本地运行示例。

dotnet run --project aspire-apphost

首次运行时,Aspire 会检查Microsoft Entra配置。 如果缺少配置值,则示例提供以交互方式运行Microsoft Entra设置流。 安装脚本创建或配置应用注册、更新 web-app/config.jsdata-api/dab-config.json启动本地资源。

Web 应用将用户重定向到Microsoft登录。 登录后,API 调用会包含 Bearer 令牌,DAB 将 preferred_username 映射到 SQL 会话上下文中,SQL RLS 仅返回匹配的行。

将示例部署到Azure。

pwsh ./azure-infra/azure-up.ps1

部署脚本为 DAB、Web 应用、模型上下文协议(MCP)检查器和 SQL 指挥官预配Azure SQL和Azure 容器应用资源。 它还使用系统分配的托管标识配置 DAB 容器应用,并运行 azure-infra/post-provision.ps1 以部署数据库、创建托管标识用户、授予数据库角色并验证 RLS 设置。

完成后,清理Azure资源和应用注册。

pwsh ./azure-infra/azure-down.ps1

清理流将删除Azure资源,并运行Microsoft Entra拆解脚本。 如果需要单独删除应用注册,请从示例 azure-infra 的文件夹运行拆解脚本。

密钥文件

路径 Purpose
data-api/dab-config.json 定义 EntraId 提供程序、authenticated 角色和 set-session-context 设置。
database/Functions/UserFilterPredicate.sql 定义将 OwnerSESSION_CONTEXT(N'preferred_username') 进行比较的 RLS 谓词函数。
database/Security/UserFilterPolicy.sql 定义 dbo.Todos 上的 UserFilterPolicy 安全策略。
web-app/auth.js 配置 MSAL、自动重定向、令牌获取和注销操作。
web-app/dab.js 随 DAB 调用发送 Authorization: Bearer <token> 标头。
web-app/config.js 存储 MSAL 的租户 ID、SPA 客户端 ID、API URL 和 API 范围。
azure-infra/post-provision.ps1 部署 dacpac、设置 Azure SQL Microsoft Entra 管理员、创建托管标识用户、授予数据库角色,以及更新 DAB 和 Web 应用设置。

使用GitHub Copilot重新创建此示例

打开要在Visual Studio Code中创建示例的工作区,将GitHub Copilot切换到代理模式,然后粘贴此提示。

You are GitHub Copilot running in agent mode. Recreate the Data API builder Quickstart 5 SQL Row-Level Security sample as a complete, runnable project in the current VS Code workspace under `quickstart-05-sql-row-level-security`. Build a static SPA with MSAL browser sign-in, DAB with Microsoft Entra bearer-token validation, SQL Server row-level security (RLS), local SQL Server with SQL authentication, Azure SQL with managed identity, REST, GraphQL, MCP, .NET Aspire, SQL Commander, MCP Inspector, and Azure Container Apps deployment scripts. DAB is the only API, GraphQL, and MCP layer over SQL. Do not create custom API code. Do not add DAB per-entity database policies; SQL RLS must enforce row filtering. Do not create or use a client secret for this quickstart.

Source repository: https://github.com/Azure-Samples/dab-2.0-quickstart-web_entra-api_entra-db_entra-db_rls. If internet access is available, inspect or clone this repository before you create files. Reuse and adapt its files as closely as possible, especially `web-app/`, `data-api/`, `database/`, `aspire-apphost/`, `mcp-inspector/`, `azure-infra/`, scripts, and README patterns. The goal is to implement the published quickstart, not to invent a different sample. If the repository differs from this prompt or the current Data API builder docs, prefer the current docs for product behavior.

Minimize user interaction. Use the defaults in this prompt and make reasonable best guesses for noncritical choices. Do not ask for a root folder or project folder name; use the current VS Code workspace and the default subfolder. Ask only when you need approval for resource changes, secrets, permissions, materially higher cost, external account choices, or an ambiguous requirement that affects the architecture.

Start with a short plan and proceed with safe defaults before you create files or run commands. Use the default `Owner nvarchar(256) NOT NULL` schema, `api://<api-app-id>/access` scope, and `preferred_username` claim-to-session-context mapping unless the user explicitly asks for different values. Ask only these questions if the values aren't already available from the environment or prior context:

- Which Azure subscription, primary region, fallback region, resource group, and tenant should the sample use? Default fallback region: `westus2` if the primary region can't provision Azure SQL or Container Apps.
- Should I create new app registrations for the SPA and API or reuse existing registrations?
- Do you approve creating billable Azure resources and Microsoft Entra app registrations if deployment starts?

If any artifact uses a different claim key, align all DAB config, SQL predicate, seed data, and validation steps to `preferred_username` and continue. Ask only if the intended claim mapping is ambiguous after inspecting the artifacts.

After the answers, show a checklist and ask for approval before implementation. Include phases for local scaffold, Entra setup, RLS schema, local validation, Azure infrastructure, Azure validation, and cleanup. Do not run `az`, `az ad`, or Azure deployment commands that create or change resources until the user explicitly approves the exact command set.

After approval, continue working without asking status-check questions. If a command, build, container, endpoint, or validation step fails, inspect the error, adjust the project, rerun the step, and continue. Keep iterating until the sample runs end-to-end or you hit a blocker that requires user action.

Use cost-first Azure defaults. Choose the cheapest option that satisfies the quickstart requirements: use a free Azure SQL database offer when the subscription and region support it; otherwise choose the lowest-cost SQL option that supports managed identity, Microsoft Entra validation, and SQL row-level security. Use Azure Container Apps consumption, minimal CPU and memory, Basic Azure Container Registry, minimal Log Analytics retention, and no always-on or dedicated plans unless required. Prioritize finishing the project. Treat regional provisioning limits as expected adjustment points, not failures: if the primary region can't provision a required service or free SQL option, use the approved fallback region such as `westus2`, and continue the deployment. Ask the user only when both the primary and fallback regions can't satisfy the requirements, when a change would materially increase cost, when a new permission is required, or when you need approval for Azure commands that create or change resources beyond the already-approved plan. Keep every resource minimal, but make the web interface neat and approachable: small code footprint, responsive layout, clear status messages, accessible labels, and simple styling that is polished rather than austere.

Verify prerequisites and report only missing items: .NET SDK, Docker Desktop running, PowerShell, Azure CLI signed in, permission to use `az ad`, `sqlpackage`, .NET Aspire tooling, and the DAB CLI. Use these docs while building:

- DAB CLI reference: https://learn.microsoft.com/azure/data-api-builder/command-line/
- `dab init` session context: https://learn.microsoft.com/azure/data-api-builder/command-line/dab-init
- `dab configure` session context: https://learn.microsoft.com/azure/data-api-builder/command-line/dab-configure
- `dab validate`: https://learn.microsoft.com/azure/data-api-builder/command-line/dab-validate
- DAB MCP overview: https://learn.microsoft.com/azure/data-api-builder/mcp/overview

Create this structure under the sample folder:

- `azure-infra/` for Bicep, `azure-up.ps1`, `azure-down.ps1`, `entra-setup.ps1`, `entra-teardown.ps1`, and `post-provision.ps1`.
- `data-api/` for `dab-config.json` and a DAB Dockerfile that bakes the config into the image for Azure.
- `database/` for a SQL Database Project with `Functions/UserFilterPredicate.sql`, `Security/UserFilterPolicy.sql`, and seed rows for at least two owners.
- `web-app/` for static HTML, CSS, and JavaScript with MSAL browser support.
- `aspire-apphost/` for the .NET Aspire AppHost.
- `mcp-inspector/` for MCP Inspector notes or container assets.

Handle generated values first. Add `.env`, `**/bin`, and `**/obj` to `.gitignore` before writing secrets or local configuration. Use `MSSQL_CONNECTION_STRING`, `ENTRA_TENANT_ID`, `ENTRA_AUDIENCE`, `ENTRA_ISSUER`, `SPA_CLIENT_ID`, and `API_SCOPE`. Never print tokens or secret values. Use `@env(...)` placeholders in `dab-config.json` where practical.

Configure DAB CORS before you start or deploy the web app. Do not leave `runtime.host.cors.origins` as `[]`. Set it to include the exact web app origins, including scheme and port: the local Aspire web origin, such as `http://localhost:5173`, and the deployed Azure Container Apps web FQDN if Azure deployment is approved. Keep `allow-credentials` set to `false` because this SPA sends bearer tokens, not browser credentials or cookies. Direct REST, GraphQL, or Swagger requests can succeed even when the browser blocks JavaScript fetch calls, so browser-origin CORS must be configured and validated separately.

Use this DAB CLI workflow and validate after each config change:

```dotnetcli
dab init --database-type mssql --connection-string "@env('MSSQL_CONNECTION_STRING')" --set-session-context true --auth.provider EntraID --auth.audience "@env('ENTRA_AUDIENCE')" --auth.issuer "@env('ENTRA_ISSUER')" --host-mode Development --rest.enabled true --graphql.enabled true --mcp.enabled true
dab add Todos --source dbo.Todos --source.type table --permissions "authenticated:read,create,update,delete" --mcp.dml-tools true
dab validate --config data-api/dab-config.json
```

Use this DAB data-source shape. `set-session-context` is required so DAB maps claims into SQL `SESSION_CONTEXT`.

```json
{
  "data-source": {
    "database-type": "mssql",
    "connection-string": "@env('MSSQL_CONNECTION_STRING')",
    "options": { "set-session-context": true }
  }
}
```

Create SQL RLS in the database project. The predicate must use the same claim name DAB sends to `SESSION_CONTEXT`; if any artifact uses a different key, align the artifacts to the approved claim mapping and continue. Ask the user only if the intended claim mapping is ambiguous.

```sql
CREATE FUNCTION dbo.UserFilterPredicate(@OwnerId sysname)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN SELECT 1 AS IsVisible
WHERE @OwnerId = CAST(SESSION_CONTEXT(N'preferred_username') AS sysname);

CREATE SECURITY POLICY UserFilterPolicy
ADD FILTER PREDICATE dbo.UserFilterPredicate(Owner) ON dbo.Todos
WITH (STATE = ON);
```

Do not add `policy.database` filters to DAB entity permissions in this quickstart. SQL RLS is the authoritative filter. Remove the `anonymous` role from protected entities so anonymous REST, GraphQL, and MCP calls to those entities are denied.

Implement the SPA with MSAL browser. `web-app/dab.js` must send bearer tokens to DAB on every protected request.

```javascript
export async function getAuthHeaders() {
  const token = await acquireAccessToken();
  return { Authorization: `Bearer ${token}` };
}
```

Use these Aspire patterns from the quickstart skills. Use `.WaitForCompletion(sqlDatabaseProject)` for DAB and SQL Commander when a SQL project deploys schema.

```csharp
var dabServer = builder.AddContainer("data-api", "azure-databases/data-api-builder", "latest")
    .WithImageRegistry("mcr.microsoft.com")
    .WithBindMount(new FileInfo("data-api/dab-config.json").FullName, "/App/dab-config.json", isReadOnly: true)
    .WithEnvironment("MSSQL_CONNECTION_STRING", sqlDatabase)
    .WithEnvironment("ENTRA_AUDIENCE", entraAudience)
    .WithEnvironment("ENTRA_ISSUER", entraIssuer)
    .WithHttpEndpoint(targetPort: 5000, name: "http")
    .WithHttpHealthCheck("/health")
    .WaitForCompletion(sqlDatabaseProject);
```

Add SQL Commander with image `jerrynixon/sql-commander:latest`, env var `ConnectionStrings__db`, and a connection string that includes `TrustServerCertificate=true`.

```csharp
var sqlCommander = builder.AddContainer("sql-cmdr", "jerrynixon/sql-commander", "latest")
    .WithImageRegistry("docker.io")
    .WithHttpEndpoint(targetPort: 8080, name: "http")
    .WithEnvironment("ConnectionStrings__db", sqlDatabase)
    .WithHttpHealthCheck("/health")
    .WaitForCompletion(sqlDatabaseProject);
```

Add MCP Inspector with Streamable HTTP transport and omit auth only for local development.

```csharp
var mcpInspector = builder.AddMcpInspector("mcp-inspector")
    .WithMcpServer(dabServer, transportType: McpTransportType.StreamableHttp)
    .WithEnvironment("DANGEROUSLY_OMIT_AUTH", "true")
    .WaitFor(dabServer);
```

For Azure, configure the DAB Container App with a system-assigned managed identity, deploy the dacpac before image validation, and bake `dab-config.json` into the DAB image. Replace web URL and CORS placeholders before image build. Do not rely on volume mounts in Azure Container Apps.

Validate before reporting success:

- `dab validate --config data-api/dab-config.json` exits with code 0.
- `dotnet run --project aspire-apphost` starts the complete local environment.
- A direct database query confirms the seeded table exists, contains rows for at least two owners, and has the RLS policy enabled.
- DAB `/health` returns a 2xx response.
- The web site returns a successful HTTP response.
- A browser-origin request from each web app origin receives an `Access-Control-Allow-Origin` response header that matches that origin.
- Anonymous REST and GraphQL requests to protected entities return `401`.
- Signed-in REST and GraphQL calls include bearer headers and reach DAB under the `authenticated` role.
- DAB sends `preferred_username` into SQL `SESSION_CONTEXT`.
- `SELECT name, is_enabled FROM sys.security_policies` shows `UserFilterPolicy` with `is_enabled = 1`.
- Two different users see different row sets when `Owner` values differ.
- The DAB configuration has `set-session-context` set to `true` and no per-entity database policies.
- MCP Inspector can connect to DAB MCP and respects authenticated access for protected entities.
- SQL Commander opens and shows seeded tables and the enabled RLS policy.
- In Azure, the DAB Container App has a system-assigned managed identity and Container Apps are healthy.

Do not report final URLs, asset locations, or a success summary until you directly verify database connectivity and query results, a 2xx DAB health response, and a successful web site response. This validation ensures the sample works without requiring the developer to check.