如何使用托管身份将 Web 应用程序连接到 Azure 上的 SQL 数据库?

问题描述 投票:0回答:1

TL;DR:我的网络应用程序连接到 SQL 的二头肌设置中缺少什么?

我是 Azure 新手,我一直在尝试为我正在从事的项目设置二头肌“堆栈”。由于某种原因,我的 Web 应用程序无法连接到 SQL 数据库。我不确定我的二头肌食谱缺少什么。

param location string = resourceGroup().location

var environment = 'myveryownproject'
var sqlDbContributorRole = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '9b7fa17d-e63e-47b0-bb0a-15c516ac86ec')

func name(abbreviation string, environment string) string => 
  '${abbreviation}-${environment}'

func uname(abbreviation string, environment string, unique string) string => 
  '${abbreviation}-${environment}-${unique}'

resource applicationsSubnet 'Microsoft.Network/virtualNetworks/subnets@2024-01-01' = {
  name: name('snet', environment)
  parent: network
  properties: {
    serviceEndpoints: [
      {
        service: 'Microsoft.Sql'
      }
    ]
    addressPrefix: '10.0.0.0/24'
    delegations: [
      {
        name: name('snetd', environment)
        properties: {
          serviceName: webAppPlan.type
        }
      }
    ]
  }
}

resource network 'Microsoft.Network/virtualNetworks@2024-01-01' = {
  name: name('vnet', environment)
  location: location
  properties: {
    addressSpace: {
      addressPrefixes: [
        '10.0.0.0/16'
      ]
    }
  }
}

resource webAppPlan 'Microsoft.Web/serverfarms@2023-12-01' = {
  name: name('asp', environment)
  location: location
  kind: 'linux'
  properties: {
    reserved: true
  }
  sku: {
    name: 'B1'
  }
}

resource webApp 'Microsoft.Web/sites@2023-12-01' = {
  name: name('app', environment)
  location: location
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    serverFarmId: webAppPlan.id
    siteConfig: {
      linuxFxVersion: 'DOTNETCORE|8.0'
    }
    httpsOnly: true
    virtualNetworkSubnetId: applicationsSubnet.id
  }
}

resource databaseServer 'Microsoft.Sql/servers@2021-11-01' = {
  name: name('sql', environment)
  location: location
  properties: {
    minimalTlsVersion: '1.2'
    administrators: {
      administratorType: 'ActiveDirectory'
      sid: '<<<MY SID>>>'
      login: '<<<MY LOGIN>>>'
      azureADOnlyAuthentication: true
      principalType: 'User'
    }
  }
  identity: {
    type: 'SystemAssigned'
  }
}

resource subnetRuleForDatabaseServer 'Microsoft.Sql/servers/virtualNetworkRules@2023-08-01-preview' = {
  name: name('sqlnet', environment)
  parent: databaseServer
  properties: {
    virtualNetworkSubnetId: applicationsSubnet.id
  }
}

resource database 'Microsoft.Sql/servers/databases@2023-08-01-preview' = {
  name: name('sqldb', environment)
  location: location
  properties: {
    zoneRedundant: false
  }
  sku: {
    name: 'GP_S_Gen5'
    tier: 'GeneralPurpose'
    family: 'Gen5'
    capacity: 1
  }
  parent: databaseServer
}

resource webAppDatabaseAccessRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(name('role', environment))
  properties: {
    principalId: webApp.identity.principalId
    roleDefinitionId: sqlDbContributorRole
  }
}

我的 Web 应用程序是一个使用 Entity Framework Core 的简单 ASP.NET Core 应用程序

var builder = WebApplication.CreateBuilder(args);
// ...
builder.Services.AddDbContext<DataContext>((sp, options) =>
{
    var configuration = sp.GetRequiredService<IConfiguration>();
    var connectionString = configuration.GetConnectionString("MyDbConnectionString");
    options.UseSqlServer(connectionString);
});
// ...
var app = builder.Build();
// ...
var conf = sp.GetRequiredService<IConfiguration>();
var connection = conf.GetConnectionString("MyDbConnectionString");
app.Logger.LogInformation($"The connection is: {connection}");
sp.GetRequiredService<DataContext>().Database.EnsureCreated();

我的应用程序在 Azure 上运行时抛出错误

Unhandled exception. Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user '<token-identified principal>'.
。如果我将自己的 IP 添加到防火墙并在本地使用相同的代码进行连接,则没有问题。我不确定我错过了什么。谢谢!

azure azure-web-app-service azure-sql-database azure-bicep azure-managed-identity
1个回答
0
投票

Web 应用程序具有 SQL DB Contributor 权限(https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles/databases#sql-db-contributor )这不允许数据访问数据库。

授予托管标识 Sql Server 管理员角色(这违反了最小权限原则)或创建包含数据库的用户(https://learn.microsoft.com/en-us/azure/azure-sql/database /authentication-aad-overview?view=azuresql#logins-server-principals) 并授予其所需的权限,例如

db_datareader
db_datawriter

© www.soinside.com 2019 - 2024. All rights reserved.