Connection string for connecting to Azure SQL Database via Azure AD - azure

How can I build connection string for connecting to Azure SQL Database using Azure AD account?
Currently, I am using the following but it does not seem to be correct. It does not use Authentication Type: Active Directory Password.
Part of PowerShell script I am using:
server=$Server.database.windows.net;initial catalog=$Databasename;Authentication=Active Directory Password;Integrated Security=False;uid=$Username;password=$Password
I really appreciate your help.

I managed to resolve the issue; It was actually the order of properties.
The following connection string worked
Data Source=$Server.database.windows.net;initial catalog=Master;User ID=$Username;password=$Password;authentication=Active Directory Password
However, this does not work
Data Source=$Server.database.windows.net;initial catalog=Master;authentication=Active Directory Password;User ID=$Username;password=$Password
The only difference is the order of "Authentication" tag.
I never thought order of properties matter in ConnectionString.

In the example, they use this format:
Data Source=n9lxnyuzhv.database.windows.net;
Authentication=Active Directory Password;
Initial Catalog=testdb;
UID=bob#contoso.onmicrosoft.com;
PWD=MyPassWord!";
So try to use PWD instead of Password.

Related

Elastic Job sp_add_jobstep returns "Cannot reference the credential because it does not exist or you do not have permission"

I'm pretty new to Azure (and SQL for that matter). I've been trying to configure Elastic Jobs Agent with a few specific jobs that would run queries against some of my databases on the server.
For right now I am targeting a test database where I want to execute a simple select query. However, I can't create the job step because of the "can't reference the credential" error.
I'm not sure why the error is popping up. I have followed Use T-SQL to create and manage Elastic Database Jobs article and I created all of the credentials and logins as described there.
The one exception here is that the masterkey already exists so I didn't create that and I also did not create a separate server for my agent host DB as suggested in some of the tutorials. My agent host DB sits on the same server where my target databases are but I would not think that would be an issue.
I have successfully created a target group and a target group member which is the specific database on this server that I want to query. I have also created the job I want to use.
The problem happens when I try to run this
DECLARE #step_id1 INT, #job_version1 INT;
EXEC jobs.sp_add_jobstep
#job_name = N'Job1',
#step_id = #step_id1 OUTPUT,
#step_name = N'Step1',
#command = N'select * from table',
#credential_name = N'agentjobuser',
#target_group_name = N'TestTarget'
I am at a loss here, I have no idea why it's saying that the credential doesn't exist. I am using the sql server admin login so I should definitely have the permissions for it.
I tried to repro this and got the same error.
When SQL server username is given as credential name parameter in the sp_add_jobstep, the same error is reproduced.
Cannot reference the credential 'user', because it does not exist or you do not have permission.
Database scoped credential name which is created for SQL server user is given as value for the parameter #credential_name. It is executed successfully without error.

Configure ODBC Azure linked service in Synapse

Where I can find the connection string in the Azure linked service for odbc as attached in screenshot. Click here for screenshot
Enter the connection String details with below format.
Driver={SQL Server};Server=Server.database.windows.net; Database=TestDatabase;
or
DSN=<name of the DSN on IR machine>;
The connection string excluding the credential portion. You can specify the connection string with pattern like Driver={SQL Server};Server=Server.database.windows.net; Database=TestDatabase;, or use the system DSN (Data Source Name) you set up on the Integration Runtime machine with DSN=<name of the DSN on IR machine>; (you need still specify the credential portion in linked service accordingly). You can also put a password in Azure Key Vault and pull the password configuration out of the connection string.
Connect via **Self hosted integrated Runtime **
Give the authentication type.
Enter username, password if authentication type is basic.
Enter the credential.
The access credential portion of the connection string specified in
driver-specific property-value format. Example: "RefreshToken=<secret refresh token>;". Mark this field as a SecureString.
Reference: MS doc on ODBC Linked Service Properties in ADF

Snowflake Role error while connecting using Python

I am trying to connect snowflake using python connector but i am facing problem while connecting to a specific role. even i have access to that role at snowflake web application but i am not able to connect with that same role using python connector. i am only able to connect with PUBLIC role.
I am using following script:
conn = snowflake.connector.connect(
user=USER,
password=PASSWORD,
role=ROLE,
account=ACCOUNT,
warehouse=WAREHOUSE,
database=DATABASE,
schema=SCHEMA,
autocommit=False
)
I am getting following error:
DatabaseError: 250001 (08001): Failed to connect to DB:
account_name.east-us-2.azure.snowflakecomputing.com:443. Role
'ANALYST_ROLE' specified in the connect string does not exist or not
authorized. Contact your local system administrator, or attempt to
login with another role, e.g. PUBLIC.
Here are some hints:
In Snowflake Role names are case sensitive. Maybe you have some quoting issues in your original code, i.e. please check your '', "", lower- or uppercase or simply use the original role name without some quotation marks.
Maybe the role has not enough privileges to operate on your db/schemas and thus it says "not authorized".
You can try to add the role manually before: Account -> Roles
I caught the error, I just made a very slight mistake(single character mistake) in my role name. due to very large name, i could not see it. I am able to connect now.
the role name mentioned here is fake for security reason so don't assume that.

Azure SQL Database - Active Directory integrated authentication

I would like to achieve following:
Avoid SQL authentication on Azure for my production configuration and use Active Directory integrated authentication
When I go to the connection string section of Azure and copy following connection string:
Server=[my server name];Initial Catalog=[my db name];Persist Security Info=False;User ID=[my user name];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication="Active Directory Integrated";
and try using it I get following exception:
Exception message: Cannot use 'Authentication=Active Directory
Integrated' with 'User ID', 'UID', 'Password' or 'PWD' connection
string keywords., Exception stacktrace: at
System.Data.SqlClient.SqlConnectionString..ctor(String
connectionString) at
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String
connectionString, DbConnectionOptions previous) at
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey
key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions&
userConnectionOptions) at
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey
key)
As I have very limited db admin/infrastructure experience I am unaware why the 'User ID' breaks everything when it is explicitly listed in the connection string I get on Azure.
A few things to note:
SQL authentication works
I have Active Directory admin set
Your connection string should look like below on C#:
string ConnectionString =
#"Data Source=n9lxnyuzhv.database.windows.net; Authentication=Active Directory Integrated; Initial Catalog=testdb;";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
Please read this documentation and this documentation for more information.
Just Try it by removing User ID part in connection string, when you are using
Authentication="Active Directory Integrated"
Server=[my server name];Initial Catalog=[my db name];Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication="Active Directory Integrated";
Try changing the IP address in your Azure database. There is a tutorial on Lynda.com on this.

Can not connect to Azure SQL Server using Active directory integrated authentication in AppService

We have web application deploy on Azure App Service. Our database is also on Azure which is configured to use AAD authentication (We have assigned AAD Admin).
We are using below connection string in web app to connect to this server and database using below connections string.
Data Source=xxxxxxx.database.windows.net;Initial
Catalog=xxxxxxx;Persist Security Info=False;Authentication=Active
Directory Integrated
Please note: This connection string is working fine when using thru local system. But getting below error when we use this conn string in Azure App Service:
Failed to authenticate the user NT Authority\Anonymous Logon in Active
Directory (Authentication=ActiveDirectoryIntegrated). Error code
0x4BC; state 10 The format of the specified domain name is invalid
According to your description, I found you used the Active Directory integrated authentication.
To use integrated Windows authentication, your domain’s Active Directory must be federated with Azure Active Directory. Your client application (or a service) connecting to the database must be running on a domain-joined machine under a user’s domain credentials
If you published the web app to Azure, Azure's web app server will not be in your domain’s Active Directory. So the SQL server will not pass the auth.
I suggest you could try to use Active Directory password authentication instead of the Active Directory integrated authentication.
Replace the connection string as below use azure AD user name and password. It will work well.
Server=tcp:brandotest.database.windows.net,1433;Initial Catalog=bradnotestsql;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication="Active Directory Password";
Since the accepted answers are a bit dated, if you are out here in 2020 or later, the correct way for setting up integrated authentication is as follows:
(excerpted from here, the asp.net standard implementation)
https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi
add the Microsoft.Azure.Services.AppAuthentication nuget package.
modify your web.config by adding: (in configSections)
<section name="SqlAuthenticationProviders" type="System.Data.SqlClient.SqlAuthenticationProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
(and then)
<SqlAuthenticationProviders>
<providers>
<add name="Active Directory Interactive" type="Microsoft.Azure.Services.AppAuthentication.SqlAppAuthenticationProvider, Microsoft.Azure.Services.AppAuthentication" />
</providers>
</SqlAuthenticationProviders>
It's important to pay attention to the name you use there. Then... your connection string will look like:
<add name="MyEntities" connectionString="metadata=res://*/Data.MyDB.csdl|res://*/Data.MyDB.ssdl|res://*/Data.MyDB.msl;provider=System.Data.SqlClient;provider connection string="server=tcp:MyDB.database.windows.net;database=MyDB;UID=AnyString;Authentication=Active Directory Interactive;"" providerName="System.Data.EntityClient" />
The important notes are that the name you specify in the SqlAuthenticationProviders section must be the exact same name you use in the connection string for Authentication.
The other important note is that, coming from your old connection strings, you have to change Data Source to be Server, and Initial Catalog to be Database. UID=AnyString is necessary, or an exception is thrown.
Failure to follow these steps exactly will net you a lovely error:
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> AdalException: The format of the specified domain name is invalid.\r\n at ADALNativeWrapper.ADALGetAccessToken(String username, IntPtr password, String stsURL, String servicePrincipalName, ValueType correlationId, String clientId, Boolean* fWindowsIntegrated, Int64& fileTime)\r\n at System.Data.SqlClient.ActiveDirectoryNativeAuthenticationProvider.<>c__DisplayClass2_0.b__0()\r\n at System.Threading.Tasks.Task`1.InnerInvoke()\r\n at System.Threading.Tasks.Task.Execute()\r\n --- End of inner exception stack trace
At the first the error doesn't make sense, but once you see that the parameters were renamed from Data Source to Server, it does make sense.
Maybe all you need to use is token (certificate) authentication as explained on below resource:
https://github.com/Microsoft/sql-server-samples/tree/master/samples/features/security/azure-active-directory-auth/token
Try to register your application with Azure Active Directory as explained on that resource.
Hope this helps.

Resources