Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Bu hızlı başlangıçta Quickstart 6 On-Behalf-Of Flow örneğini kullanarak Veri API'si oluşturucusunu (DAB) kullanıcı tarafından temsil edilen kimlik doğrulamasıyla çalıştıracaksınız. Web uygulaması, kullanıcıların Microsoft Entra ID ile oturum açmasını sağlar, taşıyıcı belirteçleri DAB’ye gönderir ve DAB, oturum açmış kullanıcı için her bir belirteci bir Azure SQL belirteciyle değiş tokuş eder.
Yerel SQL Server Microsoft Entra belirteçleri kabul edemediğinden örnek Azure SQL kullanır.
WhoAmI
SELECT SUSER_NAME() çalıştıran bir görünüm, SQL’in DAB’nin yönetilen kimliğini değil, gerçek çağıranı gördüğünü kanıtlar.
Prerequisites
- .NET 8 veya üzeri
- Docker Desktop
- PowerShell
- derleme orkestrasyonu için .NET Aspire araçları
- Microsoft Entra kurulumu ve Azure dağıtımı için Azure CLI
- Veritabanı projesini dağıtırsanız sqlpackage
- Azure SQL, Azure Container Apps, Azure Container Registry, Log Analytics ve kaynak grubu oluşturma iznine sahip bir Azure aboneliği
- Microsoft Entra uygulama kayıtları oluşturma, bir API uygulaması istemci gizli anahtarı oluşturma, Azure SQL Veritabanı için devredilmiş
user_impersonationizni ekleme ve yönetici onayı verme izni - Azure SQL için Microsoft Entra yöneticisi olabilecek Microsoft Entra kullanıcısı veya grubu
Örnek ne gösterir?
- MSAL tarayıcı oturum açmasını kullanan statik bir web uygulaması.
- Web uygulamasından DAB'ye bearer token çağrıları.
- DAB, Microsoft Entra ID
EntraIdkimlik doğrulama sağlayıcısıyla yapılandırılır. - OBO belirteci değişimi için yapılandırılan DAB
user-delegated-auth. - OBO değiş tokuşu için istemci gizli anahtarına sahip bir API uygulama kaydı.
- Azure SQL Veritabanı için yönetici onayıyla
user_impersonationtemsilci izni verildi. -
User ID,PasswordveyaAuthenticationanahtar sözcüğü olmayan çıplak bir Azure SQL bağlantı dizesi. - Anonim erişimi olmayan kimliği doğrulanmış DAB varlıkları.
- Oturum açmış arayanlar için bağımsız Azure SQL kullanıcıları.
- SQL çağıranın kimliğini doğrulamak için
SUSER_NAME()döndüren birWhoAmIgörünüm. -
azure-infraiçindeki PowerShell betikleri aracılığıyla Azure dağıtımı ve temizleme
Kimlik doğrulama akışı
| Atlama | Authentication |
|---|---|
| Kullanıcı ile web uygulaması arasında | Microsoft Entra ID ile MSAL tarayıcısında oturum açma |
| Web uygulamasından DAB API'sine | DAB API hedef kitlesi için taşıyıcı belirteci |
| DAB API rolü | authenticated |
| DAB'den Azure SQL'e | Fiilen oturum açmış kullanıcı için OBO belirteci |
Seriyle karşılaştırma
| Step | Hangi değişiklikler |
|---|---|
| Previous | SQL satır düzeyi güvenlik, SQL'deki satırları filtreler, ancak SQL yine de DAB hizmet kimliğinin kimliğini doğrular. |
| Bu hızlı başlangıç | Azure SQL’in denetim ve kullanıcıya duyarlı ilkeler için gerçekte oturum açan kullanıcıyı kimlik doğrulamasıyla tanıyabilmesi amacıyla OBO kullanır. |
| İleri | OBO kimlik doğrulamasını yapılandırma , OBO yapılandırma özelliklerini ayrıntılı olarak açıklar. |
Yalnızca Azure’a özgü davranış
OBO, Microsoft Entra kimlik doğrulamasıyla Azure SQL gerektirir. Yerel bir SQL Server kapsayıcısı Microsoft Entra belirteçlerini kabul edemediğinden, tam OBO akışı yalnızca Azure ile sınırlıdır.
DAB'nin kimliği doğrulanmış her isteğe kullanıcı başına OBO belirtecini ekleyebilmesi için çıplak bir Azure SQL bağlantı dizesi kullanın.
Server=tcp:<server>.database.windows.net,1433;Database=<database>;Encrypt=True;TrustServerCertificate=False;
Bu değerleri OBO bağlantı dizesine dahil etmeyin:
User IDPasswordAuthentication
Important
bağlantı dizesi Authentication= içeriyorsa, DAB bir erişim belirteci de sağladığında SQL istemci kitaplıkları isteği reddeder.
Örneği kullanma
Örnek depoyu kopyalayın.
git clone https://github.com/Azure-Samples/dab-2.0-quickstart-web_entra-api_entra-db_entra-obo.git
cd dab-2.0-quickstart-web_entra-api_entra-db_entra-obo
Yerel araçları geri yükleyin.
dotnet tool restore
Azure'da oturum açın.
az login
Örneği Azure dağıtın.
pwsh ./azure-infra/azure-up.ps1
Dağıtım betiği DAB, web uygulaması, MCP Denetçisi ve SQL Commander için Azure SQL ve Azure Container Apps kaynakları sağlar. Ayrıca Microsoft Entra kurulumunu gerçekleştirir, API uygulaması için istemci gizli anahtarı oluşturur, Azure SQL Veritabanı için devredilmiş user_impersonation iznini ekler, yönetici onayını verir, veritabanını dağıtır, içerilen kullanıcılar oluşturur ve DAB'yi OBO için yapılandırır.
Dağıtımdan sonra betiğin yazdırdığı web uygulaması URL'sini açın. Oturum açın ve SQL Server sees you as rozetinin kullanıcı asıl adınızı gösterdiğini doğrulayın. Rozet, SELECT SUSER_NAME() tarafından desteklenen WhoAmI varlığını okur.
Anonim API isteklerinin 401 Unauthorized döndürmesi gerekir.
İşiniz bittiğinde Azure kaynakları ve uygulama kayıtlarını temizleyin.
pwsh ./azure-infra/azure-down.ps1
Anahtar dosyaları
| Yol | Purpose |
|---|---|
data-api/dab-config.json |
user-delegated-auth öğesini etkinleştirir, önbelleği devre dışı bırakır, EntraId öğesini yapılandırır ve WhoAmI görünüm varlığını kullanıma sunar. |
database/Views/WhoAmI.sql |
Kimlik doğrulaması için tanımlar SELECT SUSER_NAME() AS UserName . |
web-app/index.html |
Oturum açmış kullanıcıyı ve SQL kimliği rozetini gösterir. |
web-app/app.js |
Oturum açma, sayfa güncelleştirmeleri ve kimlik yenilemeyi koordine eder. |
web-app/dab.js |
DAB'ye taşıyıcı belirteci istekleri gönderir ve WhoAmI öğesini okur. |
azure-infra/entra-setup.ps1 |
Microsoft Entra uygulama kayıtları oluşturur, API istemci gizli anahtarını oluşturur, Azure SQL Veritabanı için devredilmiş user_impersonation iznini ekler ve yönetici onayı sağlar. |
azure-infra/resources.bicep |
Azure kaynakları tanımlar ve çıplak Azure SQL bağlantı dizesi ve OBO ayarlarını DAB'ye geçirir. |
azure-infra/post-provision.ps1 |
Veritabanını dağıtır, Azure SQL Microsoft Entra yöneticisini ayarlar, içerilen kullanıcılar oluşturur ve OBO ortam değerlerini yapılandırır. |
Bu örneği yeniden oluşturmak için GitHub Copilot kullanın
Örneği oluşturmak istediğiniz çalışma alanını Visual Studio Code’da açın, GitHub Copilot’u ajan moduna geçirin ve bu istemi yapıştırın.
You are GitHub Copilot running in agent mode. Recreate the Data API builder Quickstart 6 On-Behalf-Of Flow sample as a complete Azure-only project in the current VS Code workspace under `quickstart-06-on-behalf-of`. Build a static SPA with MSAL browser sign-in, DAB with Microsoft Entra bearer-token validation and OBO user-delegated authentication, Azure SQL, REST, GraphQL, MCP, .NET Aspire build orchestration, SQL Commander, MCP Inspector, and Azure Container Apps deployment scripts. DAB is the only API, GraphQL, and MCP layer over SQL. SQL must authenticate the actual signed-in user, not the DAB managed identity or service principal.
Source repository: https://github.com/Azure-Samples/dab-2.0-quickstart-web_entra-api_entra-db_entra-obo. 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.
Azure-only constraint: do not build a local SQL Server OBO path. Local SQL Server cannot accept Microsoft Entra tokens. Use local tooling only for project generation, web app development, DAB config validation where possible, container builds, and database package builds.
Start with a short plan and proceed with safe defaults before you create files or run commands. Use the default `WhoAmI` view unless the user explicitly asks for additional schema. 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 SPA and API app registrations or reuse existing registrations?
- Confirm that the API app can use a client secret. OBO requires a confidential client.
- Confirm that the API app should receive Azure SQL Database delegated `user_impersonation` permission and admin consent.
- Which Microsoft Entra user or group should become the Azure SQL Microsoft Entra admin?
- Which signed-in users or groups should become contained database users for validation?
- Do you approve creating billable Azure resources, app registrations, and an API app client secret if deployment starts?
After the answers, show a checklist and ask for approval before implementation. Include phases for scaffold, Entra setup, database package, Azure infrastructure, post-provision, validation, and cleanup. Do not run `az`, `az ad`, `azd`, 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 and it supports Microsoft Entra/OBO validation; otherwise choose the lowest-cost SQL option that supports user-delegated authentication. 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 create app registrations and grant admin consent, `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 configure` OBO options: 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
- OBO concept: https://learn.microsoft.com/azure/data-api-builder/concept/security/authenticate-on-behalf-of
- User-delegated auth configuration: https://learn.microsoft.com/azure/data-api-builder/configuration/data-source#user-delegated-auth
Create this structure under the sample folder:
- `azure-infra/` for Bicep, `azure-up.ps1`, `azure-down.ps1`, `entra-setup.ps1`, `entra-teardown.ps1`, `resources.bicep`, and `post-provision.ps1`.
- `data-api/` for `dab-config.json` and a DAB Dockerfile that bakes the config into the image.
- `database/` for a SQL Database Project, seed data, and `Views/WhoAmI.sql`.
- `web-app/` for static HTML, CSS, and JavaScript with MSAL browser support.
- `aspire-apphost/` for build orchestration only.
- `mcp-inspector/` for MCP Inspector container assets and nginx same-origin proxy config.
Handle secrets first. Add `.env`, `**/bin`, and `**/obj` to `.gitignore` before writing secrets or local configuration. Store the API client secret only in local `.env` files for local preparation and in Azure Key Vault or Azure Container Apps secrets for Azure. Never inline secret values in Bicep, PowerShell scripts, generated JSON, logs, or reports. Generate secret references for Container Apps instead of plaintext environment values. Never print tokens, passwords, or client secret values. Redact all secret values as `***redacted***`.
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: any local web origin used for development and the deployed Azure Container Apps web FQDN. 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 for config shaping and validation where possible:
```dotnetcli
dab init --database-type mssql --connection-string "@env('DATABASE_CONNECTION_STRING')" --auth.provider EntraID --auth.audience "@env('ENTRA_AUDIENCE')" --auth.issuer "@env('ENTRA_ISSUER')" --rest.enabled true --graphql.enabled true --mcp.enabled true
dab configure --data-source.user-delegated-auth.enabled true --data-source.user-delegated-auth.provider EntraId --data-source.user-delegated-auth.database-audience "https://database.windows.net"
dab add WhoAmI --source dbo.vw_WhoAmI --source.type view --source.key-fields "UserName" --permissions "authenticated:read" --mcp.dml-tools true
dab validate --config data-api/dab-config.json
```
Use a bare Azure SQL connection string so DAB can inject the per-user OBO access token. Do not include `User ID`, `Password`, or `Authentication`.
```text
Server=tcp:<server>.database.windows.net,1433;Database=<database>;Encrypt=True;TrustServerCertificate=False;
```
Use this DAB data-source shape for OBO:
```json
{
"data-source": {
"database-type": "mssql",
"connection-string": "@env('DATABASE_CONNECTION_STRING')",
"user-delegated-auth": {
"enabled": true,
"provider": "EntraId",
"database-audience": "https://database.windows.net"
}
}
}
```
Create `database/Views/WhoAmI.sql` to prove SQL sees the signed-in user.
```sql
CREATE VIEW dbo.vw_WhoAmI AS
SELECT CAST(SUSER_NAME() AS nvarchar(256)) AS UserName;
```
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}` };
}
```
For Azure, bake `dab-config.json` into the DAB image. Do not rely on volume mounts in Azure Container Apps.
```dockerfile
FROM mcr.microsoft.com/azure-databases/data-api-builder:latest
COPY dab-config.json /App/dab-config.json
```
Before any Azure post-provision command, list the exact `az`, `az acr`, `az containerapp`, and `sqlpackage` commands you intend to run and wait for explicit user approval. Post-provision in this order: deploy dacpac, set the Azure SQL Microsoft Entra admin, create contained database users or groups for validation, grant access to demo objects and `WhoAmI`, replace placeholders, build and push the DAB image, then update Container Apps.
```powershell
dotnet build database/database.sqlproj -c Release
sqlpackage /Action:Publish /SourceFile:database/bin/Release/database.dacpac /TargetConnectionString:"$sqlConn" /p:BlockOnPossibleDataLoss=false
az acr build --registry $acrName --image dab-api:latest --file ./data-api/Dockerfile ./data-api/
az containerapp update --name $dabAppName --resource-group $resourceGroup --image "$acrName.azurecr.io/dab-api:latest"
```
Deploy MCP Inspector with a same-origin proxy pattern and set `MCP_SERVER_URL` to the DAB `/mcp` endpoint.
```nginx
location /mcp {
proxy_pass http://127.0.0.1:6277;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_buffering off;
}
```
Deploy SQL Commander with env var `ConnectionStrings__db` and ensure the connection string includes `TrustServerCertificate=true`.
```text
ConnectionStrings__db=Server=<server>.database.windows.net;Database=<database>;User Id=<user>;Password=<password>;TrustServerCertificate=true
```
Validation must prove OBO, not only API authentication:
- A direct Azure SQL query confirms the database is reachable, the deployed objects exist, and required contained users or groups exist.
- 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.
- The web app signs in with Microsoft Entra ID.
- Signed-in REST, GraphQL, and MCP calls include bearer headers and reach DAB under the `authenticated` role.
- The `WhoAmI` entity returns the signed-in user's UPN from `SUSER_NAME()`.
- `WhoAmI` does not return the DAB managed identity, service principal, or Container App identity.
- Anonymous REST and GraphQL calls return `401`.
- The DAB Container App database connection string contains no SQL password, no `User ID`, and no `Authentication` keyword.
- The API client secret exists only as a secret reference or redacted local value.
- MCP Inspector connects to DAB MCP with streamable HTTP.
- SQL Commander can browse the deployed schema.
- Required contained users or groups exist in Azure SQL.
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.
Troubleshoot with these checks:
- OBO token exchange fails: verify the API app has Azure SQL Database delegated `user_impersonation` permission and admin consent.
- SQL login fails for a token-identified principal: add the signed-in user or group as a contained user in the database.
- DAB returns 401 for valid bearer tokens: verify audience and issuer values in `dab-config.json`.
- SQL sees the service identity instead of the user: verify `user-delegated-auth`, the API client secret, and the bare SQL connection string.
İlgili içerik
- Data API Oluşturucusu hızlı başlangıç
- Hızlı Başlangıç: Veri API oluşturucusu ile SQL satır düzeyi güvenliği kullanma
- Başkası adına kullanıcı tarafından devredilen kimlik doğrulamasını yapılandırma
- Kullanıcı Yetkilendirme Yapılandırma Referansı
- Hızlı başlangıç: Data API builder'a bir Microsoft Entra sağlayıcısı ekleme
- Veri API oluşturucusunda Microsoft Entra ID kimlik doğrulaması
- Veri API oluşturucusu sürüm 2.0'daki yenilikler