当前位置: 首页 > news >正文

Azure App Service连接Azure SQL MI

  前言

  最近,在研究云迁移,做了个测试如何使用App Service连接SQL MI。

  正文

  1.测试项目是Net Framework v4.8,核心代码如下图:

 1 StringBuilder message = new StringBuilder();
 2 try
 3 {
 4     string sqlstr = "Server=smi-test.c5c92fb776c2.database.windows.net;Database=test;Authentication=Active Directory Managed Identity;Encrypt=True";
 5     SqlConnection connection = new SqlConnection(sqlstr);
 6 
 7     connection.Open();
 8     message.AppendLine("opened");
 9     SqlCommand cmd = new SqlCommand("SELECT TOP (1000) [ID],[Text] FROM [test].[dbo].[Table1]", connection);
10     SqlDataAdapter ada = new SqlDataAdapter(cmd);
11     DataTable dt = new DataTable();
12     ada.Fill(dt);
13     message.AppendLine("row count: " + dt.Rows.Count.ToString());
14     foreach (DataRow dr in dt.Rows)
15     {
16         message.AppendLine(dr["ID"].ToString() + dr["Text"].ToString());
17     }
18     connection.Close();
19 
20 }
21 catch (Exception ex)
22 {
23     message.AppendLine(ex.Message.ToString());
24     message.AppendLine(ex.StackTrace.ToString());
25 }

  2.SQL Server用的是SQL MI,如下图:

image

  3.这是使用的是System assigned托管标识,需要先用PowerShell命令给一下Graph API的权限,才可以使用,否则找不到,如下图:

# Script to assign permissions to an existing UMI 
# The following required Microsoft Graph permissions will be assigned: 
#   User.Read.All
#   GroupMember.Read.All
#   Application.Read.AllImport-Module Microsoft.Graph.Authentication
Import-Module Microsoft.Graph.Applications$tenantId = "xxxxxxxx-xxxx-xxxx-xxxxxxxx" # Your tenant ID
$MSIName = "appserviceforsqlmi"; # Name of your managed identity# Log in as a user with the "Privileged Role Administrator" role
Connect-MgGraph -TenantId $tenantId -Scopes "AppRoleAssignment.ReadWrite.All,Application.Read.All"# Search for Microsoft Graph
$MSGraphSP = Get-MgServicePrincipal -Filter "DisplayName eq 'Microsoft Graph'";
$MSGraphSP# Sample Output# DisplayName     Id                                   AppId                                SignInAudience      ServicePrincipalType
# -----------     --                                   -----                                --------------      --------------------
# Microsoft Graph 47d73278-e43c-4cc2-a606-c500b66883ef 00000003-0000-0000-c000-000000000000 AzureADMultipleOrgs Application$MSI = Get-MgServicePrincipal -Filter "DisplayName eq '$MSIName'" 
if($MSI.Count -gt 1)
{ 
Write-Output "More than 1 principal found with that name, please find your principal and copy its object ID. Replace the above line with the syntax $MSI = Get-MgServicePrincipal -ServicePrincipalId <your_object_id>"
Exit
}# Get required permissions
$Permissions = @("User.Read.All""GroupMember.Read.All""Application.Read.All"
)# Find app permissions within Microsoft Graph application
$MSGraphAppRoles = $MSGraphSP.AppRoles | Where-Object {($_.Value -in $Permissions)}# Assign the managed identity app roles for each permission
foreach($AppRole in $MSGraphAppRoles)
{$AppRoleAssignment = @{principalId = $MSI.IdresourceId = $MSGraphSP.IdappRoleId = $AppRole.Id}New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $AppRoleAssignment.PrincipalId -BodyParameter $AppRoleAssignment -Verbose
}

  4.使用sql语句加权限,如下图:

CREATE USER [appserviceforsqlmi] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [appserviceforsqlmi];

  5.然后部署app Service就行了

  总结

  这里需要注意的连接sql的时候要用Microsoft.Data.Client,不要用System的。

http://www.wxhsa.cn/company.asp?id=5030

相关文章:

  • 将目标数据复制到服务器-ServerSetReplicatedTargetData()
  • 不是说 PHP 不行了吗?为什么 Swoole 还在更新?
  • qoj1831 Bruteforce
  • C++数据结构和算法:链表
  • CAI:开源网络安全AI框架,打造自主安全测试智能体
  • GAS中,负责封装技能所影响的目标数据(如 Actor、位置、碰撞结果等)-FGameplayAbilityTargetData
  • 详细介绍:Maven入门_简介、安装与配置
  • 实用指南:立体校正原理
  • train-labels.idx1-ubyte里是什么
  • 滑动窗口最大值-leetcode
  • 创建预测窗口-ScopedPredictionWindow();
  • 95. 不同的二叉搜索树 II
  • lc1028-从先序遍历还原二叉树
  • P12558 [UOI 2024] Heroes and Monsters 题解
  • 加把劲——2025 年中总结
  • Ability-GetCurrentActorInfo()-IsLocallyControlled()和APawn::IsLocallyControlled()
  • 应该遵守的代码规范与读《数学之美》有感
  • AbilitySystemComponent和AbilityTask
  • AT_arc171_c [ARC171C] Swap on Tree
  • 202509_QQ_冷门的Base家族
  • SpawnActorDeferred()和SpawnActorOfClass()
  • 【QT】信号和槽
  • 学习日报|线程池专题学习总结 - 详解
  • 如何设计业务架构 - 智慧园区
  • snmp协议
  • 刷题复习(四)二分搜索
  • aardio | 通过点击checkbox复选框本身判断是否勾选
  • 项目介绍
  • 新媒体运营用AI排版工具|10分钟搞定公众号图文的全流程指南
  • 练习第一天学习的内容