Error Login failed for user ''.' when i try to connect through azure active directory interceptor in my solution

Viewed 195

I am implementing the Azure active directory interceptor to connect my solution through active directory. My username is already added in the azure database and I am using below class as interceptor with like below.

    public class AadAuthenticationDbConnectionInterceptor : DbConnectionInterceptor
    {
        public override InterceptionResult ConnectionOpening();
        public override async Task<InterceptionResult> ConnectionOpeningAsync();
    }

Its connecting fine through SSMS with the account but when I connect through my solution in visual studio it gives me below error:

Microsoft.Data.SqlClient.SqlException: 'Login failed for user ''.'

Help will be appreciated.

1 Answers

You need to use Azure Identity:

var resourceScope = "https://database.windows.net/.default";
var tokenCredential = new DefaultAzureCredential();
var accessToken = tokenCredential.GetToken(
      new TokenRequestContext(scopes: new string[] { resourceScope }) { }
    );
using (var connection = new SqlConnection($"Server={dbserver};Initial Catalog={db};Encrypt=True;TrustServerCertificate=True"))
{
        connection.AccessToken = accessToken.Token;
        connection.Open();
}
Related