使用托管标识将 Azure SQL 数据库连接到 Azure Spring Cloud 应用Use a managed identity to connect Azure SQL Database to an Azure Spring Cloud app

本文介绍如何为 Azure Spring Cloud 应用创建托管标识,并使用该标识来访问 Azure SQL 数据库。This article shows you how to create a managed identity for an Azure Spring Cloud app and use it to access Azure SQL Database.

Azure SQL 数据库是面向云生成的一项可缩放的智能关系数据库服务。Azure SQL Database is the intelligent, scalable, relational database service built for the cloud. 它始终处于最新状态,具有 AI 支持的自动化功能,可优化性能和持续性。It’s always up to date, with AI-powered and automated features that optimize performance and durability. 无服务器计算和超大规模存储选项会自动按需缩放资源,因此你可以专注于构建新的应用程序,而无需担心存储大小或资源管理。Serverless compute and Hyperscale storage options automatically scale resources on demand, so you can focus on building new applications without worrying about storage size or resource management.

必备条件Prerequisites

此示例使用以下资源。This example uses the following resources.

向托管标识授予权限Grant permission to the Managed Identity

连接到 SQL Server 并运行以下 SQL 查询:Connect to your SQL server and run the following SQL query:

CREATE USER [<MIName>] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [<MIName>];
ALTER ROLE db_datawriter ADD MEMBER [<MIName>];
ALTER ROLE db_ddladmin ADD MEMBER [<MIName>];
GO

此 遵循 <service instance name>/apps/<app name> 规则,如 myspringcloud/apps/sqldemo。This follows the rule: <service instance name>/apps/<app name>, e.g myspringcloud/apps/sqldemo. 还可以通过 Azure CLI 查询 MIName:You can also query the MIName with Azure CLI:

az ad sp show --id <identity object ID> --query displayName

配置 Java 应用以使用托管标识Configure your Java app to use Managed Identity

打开 src/main/resources/application.properties 文件,并在下面一行的末尾添加 Authentication=ActiveDirectoryMSI;Open the src/main/resources/application.properties file, and add Authentication=ActiveDirectoryMSI; at the end of the following line. 请确保为 $AZ_DATABASE_NAME 变量使用正确的值。Be sure to use the correct value for $AZ_DATABASE_NAME variable.

spring.datasource.url=jdbc:sqlserver://$AZ_DATABASE_NAME.database.chinacloudapi.cn:1433;database=demo;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.chinacloudapi.cn;loginTimeout=30;Authentication=ActiveDirectoryMSI;

生成应用并将其部署到 Azure Spring CloudBuild and deploy the app to Azure Spring Cloud

重新生成应用,并将其部署到先决条件下第二个项目符号点中预配的 Azure Spring Cloud 应用。Rebuild the app and deploy it to the Azure Spring Cloud app provisioned in the second bullet point under Prerequisites. 现在,你有了一个通过托管标识进行身份验证的 Spring Boot 应用程序,该应用程序使用 JPA 在 Azure Spring Cloud 中的 Azure SQL 数据库中存储和检索数据。Now you have a Spring Boot application, authenticated by a Managed Identity, that uses JPA to store and retrieve data from an Azure SQL Database in Azure Spring Cloud.

后续步骤Next steps