问题描述
在App Service中启用Identity后,使用系统自动生成 Identity。
使用如下代码连接数据库 SQL Server:
SQLServerDataSource dataSource = new SQLServerDataSource(); dataSource.setServerName("yoursqlservername.database.chinacloudapi.cn"); // Replace with your server name dataSource.setDatabaseName("db name"); // Replace with your database name dataSource.setAuthentication("ActiveDirectoryMSI"); // Optional dataSource.setMSIClientId("your app service systemd identity id"); // Replace with Client ID of User-Assigned Managed Identity to be used
执行报错:
ERROR 156 --- [ Thread-8] c.a.identity.ManagedIdentityCredential : Azure Identity => ERROR in getToken() call for scopes [https://database.chinacloudapi.cn//.default]: Managed Identity authentication is not available.
ERROR 156 --- [p-nio-80-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.azure.identity.CredentialUnavailableException: Managed Identity authentication is not available.]
问题解答
================================================================================================================
其实,问题最关键的地方就是这句代码
dataSource.setMSIClientId("your app service systemd identity id"); // Replace with Client ID of User-Assigned Managed Identity to be used
参考文档中给出的示例代码这这句代码的要求是可选(Optional),并且说明是 当使用 User-Assigned Managed Identity的时候替换成自己的ID。
并没有说当使用System Managed Identity的时候也需要啊。
当写代码时,不小心,没有理解这句话,就会不由自主的把 System Managed Identity 的ID 添加到代码 dataSource.setMSIClientId("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
就会导致了这次错误。
=================================================================================================================
所以,当使用System Managed Identity时,正确的连接代码其实很简单,就是:
SQLServerDataSource dataSource = new SQLServerDataSource(); dataSource.setServerName("yoursqlservername.database.chinacloudapi.cn"); // Replace with your server name dataSource.setDatabaseName("db name"); // Replace with your database name dataSource.setAuthentication("ActiveDirectoryMSI");
只有当使用的时User Managed Identity时候,才加上下面这句代码:
dataSource.setMSIClientId("your app service user identity id"); // Replace with Client ID of User-Assigned Managed Identity to be used
参考资料
使用 Azure Active Directory 身份验证进行连接 : https://learn.microsoft.com/zh-cn/sql/connect/jdbc/connecting-using-azure-active-directory-authentication?view=sql-server-ver16