I have mvc 5 application that is targeting .net framework 4.8. I am trying to connect to the Azure sql db using managed identity locally but getting the following error:
login failed for user token-identified principal>
I’ve spent many hours but was unable to find any good solution.
Steps I’ve performed:
- Set the AD group (which I am part of) as an Admin of the Sql Server. Also tried my user as ad admin directly.
- Set my user under "Azure Service Authentication" in VS 2022
- Created my user in the db
CREATE USER [myUSer] FROM EXTERNAL PROVIDER;
and assigned db_datareader and db_datawriter role - Removed user id and password from the connection and it only has the Server and Database. Also checked that the db name has no typo.
- Whitelisted my IP in db firewalls.
- Updated code so it uses AccessToken on the SqlConnection
.
using(var connection = new Microsoft.Data.SqlClient.SqlConnection(connString))
{
var credential = new DefaultAzureCredential(){};
var token = credential.GetToken(new TokenRequestContext(new[] { "https://database.windows.net/.default" }));
connection.AccessToken = token.Token;
connection.Open();
}
But as soon as it calls the connection.Open() I start getting the login failed error. What am I missing here?
2
Answers
So there were actually two issues. I wasn't passing the AD TenantId which was different for SqlServer Admins, so I passed the TenantId with the DefaultAzureCredential:
Also i set some Environment variables for accessing KeyVault locally and those variables were overriding some of the config values which I could see in the token generated by DefaultAzureCredential. So deleting the variables and setting up the TenantId solved the problem for me.
Install packages:
Install-Package Azure.Identity -Version 1.4.0
Install-Package System.Data.SqlClient -Version 4.8.2
Added my
IP address
in DB firewall.Here is the code that worked for me:
Output results from database:
Ms Doc Reference