简体   繁体   中英

Azure SQL authentication using Azure Active Directory

Connection works fine following this tutorial when using:

var connection = (SqlConnection)Database.GetDbConnection();
connection.AccessToken = (new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;

But now the docs say "Microsoft.Azure.Services.AppAuthentication is no longer recommended"

So changing my connection as described in Using Azure Active Directory authentication with SqlClient I get the following errors:

Integrated Windows Auth is not supported for managed users.

Tried to get token using Managed Identity. Access token could not be acquired. A socket operation was attempted to an unreachable network. (169.254.169.254:80)

Nothing is blocking that address, but also where is it getting that IP from? The tutorial's code used https://database.windows.net/ to get the token (which resolves 65.55.23.107).

Can/should I override that address somewhere?
Any other config missing?

These auth ways apply to different scenarios, for example, if you want to use Active Directory Integrated authentication , you need to federate the on-premises AD with Azure AD via ADFS, if you want to use Active Directory Managed Identity authentication , you must run your code in an Azure service which supports MSI(need to enable MSI first) , because the code essentially makes an API call to the azure instance metadata endpoint to get the access token, then use the token to auth, it is just available in the MSI-supported service.

So if you want to migrate the code from the old sdk to the new one, you need to choose the correct auth way that applies to your scenario. Here I recommend you to use the Active Directory Service Principal authentication , it can apply to any scenario, please follow the steps below.

1. Register an application with Azure AD and create a service principal .

2. Get values for signing in and create a new application secret .

3. Grant the permission to the service principal with CREATE USER [Azure_AD_Object] FROM EXTERNAL PROVIDER .

4.Then use the code here , fix the values with yours and got from step 2.

string ConnectionString = @"Server=demo.database.windows.net; Authentication=Active Directory Service Principal; Database=testdb; User Id=AppId; Password=secret";

using (SqlConnection conn = new SqlConnection(ConnectionString)) {
    conn.Open();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM