Connecting to Azure SQL from App Service using AAD identity












0















An on-premise web application (.net 4.6.1) which uses Windows Authentication for its users and then AD Integrated Authentication to connect to a MS SQL database is been migrated to Azure.



Ideally, the existing security mechanism of granting permissions to AD users on database objects and let the DB be security source of the application should be kept.



A copy of the SQL database has already been created and configured.



If I run the web application locally but using the new Azure database everything works as expected.



If I run this command I get the expected AD user:



SELECT CURRENT_USER;


Now, when I deploy exactly the same application to an Azure App Service and enable Azure Active Directory Authentication and Managed Service Identity, the user is authenticated correctly on the Web application but it is not able to connect to the SQL database and the following error is returned:




Errors = System.Data.SqlClient.SqlErrorCollection ClientConnectionId =
e9f0c48a-3159-465c-ab72-c1da99761b8f Class = 14 LineNumber = 65536
Number = 18456 Procedure = Server =
xxxxxxxxxxx.tr4.canadacentral1-a.worker.database.windows.net,11057
State = 1 Source = .Net SqlClient Data Provider ErrorCode =
-2146232060 Message = Login failed for user 'NT AUTHORITYANONYMOUS LOGON'




If I disable Managed Service Identity, I get this error instead:




InnerExceptions =
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Exception]
Message = One or more errors occurred. Data =
System.Collections.ListDictionaryInternal InnerException =
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException:
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried the following 4 methods to get an access token, but
none of them worked. Parameters: Connection String: [No connection
string specified], Resource: https://database.windows.net/, Authority:
. Exception Message: Tried to get token using Managed Service
Identity. Unable to connect to the Managed Service Identity (MSI)
endpoint. Please check that you are running on an Azure resource that
has MSI setup. Parameters: Connection String: [No connection string
specified], Resource: https://database.windows.net/, Authority: .
Exception Message: Tried to get token using Visual Studio. Access
token could not be acquired. Visual Studio Token provider file not
found at
"D:localLocalAppData.IdentityServiceAzureServiceAuthtokenprovider.json"
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried to get token using Azure CLI. Access token could not be
acquired. 'az' is not recognized as an internal or external command,
operable program or batch file. Parameters: Connection String: [No
connection string specified], Resource: https://database.windows.net/,
Authority: https://login.microsoftonline.com/common. Exception
Message: Tried to get token using Active Directory Integrated
Authentication. Access token could not be acquired.
get_user_name_failed: Failed to get user nameInner Exception : The
format of the specified domain name is invalidat
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.d__14.MoveNext()




Is it what I'm trying to do possible? If yes, what am I missing? Any thoughts will be appreciated.



For reference, this is the method returning the SQL connection:



private SqlConnection GetSqlConnection()
{
var accessToken = new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").Result;

return new SqlConnection
{
ConnectionString = WebConfigurationManager.ConnectionStrings["Default"].ConnectionString,
AccessToken = accessToken
};
}


... and this is the connection string:



  <connectionStrings>
<add name="Default" connectionString="Data Source=myserver.database.windows.net;Initial Catalog=MyDB;" providerName="System.Data.SqlClient" />
</connectionStrings>


Note: The local AD is been synchronized with its Azure AD counterpart.










share|improve this question

























  • Please try the steps provided on this article: colinsalmcorner.com/post/…

    – Alberto Morillo
    Nov 15 '18 at 14:40











  • AAD is enabled for the database already. My question is, once I connect to SQL and run "SELECT CURRENT_USER", am I going to get the App Service user or the original AD credentials for the user?

    – JCallico
    Nov 15 '18 at 16:48











  • Any process now? If you still have any problem, please feel free to let me know.

    – Joey Cai
    Nov 20 '18 at 7:20
















0















An on-premise web application (.net 4.6.1) which uses Windows Authentication for its users and then AD Integrated Authentication to connect to a MS SQL database is been migrated to Azure.



Ideally, the existing security mechanism of granting permissions to AD users on database objects and let the DB be security source of the application should be kept.



A copy of the SQL database has already been created and configured.



If I run the web application locally but using the new Azure database everything works as expected.



If I run this command I get the expected AD user:



SELECT CURRENT_USER;


Now, when I deploy exactly the same application to an Azure App Service and enable Azure Active Directory Authentication and Managed Service Identity, the user is authenticated correctly on the Web application but it is not able to connect to the SQL database and the following error is returned:




Errors = System.Data.SqlClient.SqlErrorCollection ClientConnectionId =
e9f0c48a-3159-465c-ab72-c1da99761b8f Class = 14 LineNumber = 65536
Number = 18456 Procedure = Server =
xxxxxxxxxxx.tr4.canadacentral1-a.worker.database.windows.net,11057
State = 1 Source = .Net SqlClient Data Provider ErrorCode =
-2146232060 Message = Login failed for user 'NT AUTHORITYANONYMOUS LOGON'




If I disable Managed Service Identity, I get this error instead:




InnerExceptions =
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Exception]
Message = One or more errors occurred. Data =
System.Collections.ListDictionaryInternal InnerException =
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException:
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried the following 4 methods to get an access token, but
none of them worked. Parameters: Connection String: [No connection
string specified], Resource: https://database.windows.net/, Authority:
. Exception Message: Tried to get token using Managed Service
Identity. Unable to connect to the Managed Service Identity (MSI)
endpoint. Please check that you are running on an Azure resource that
has MSI setup. Parameters: Connection String: [No connection string
specified], Resource: https://database.windows.net/, Authority: .
Exception Message: Tried to get token using Visual Studio. Access
token could not be acquired. Visual Studio Token provider file not
found at
"D:localLocalAppData.IdentityServiceAzureServiceAuthtokenprovider.json"
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried to get token using Azure CLI. Access token could not be
acquired. 'az' is not recognized as an internal or external command,
operable program or batch file. Parameters: Connection String: [No
connection string specified], Resource: https://database.windows.net/,
Authority: https://login.microsoftonline.com/common. Exception
Message: Tried to get token using Active Directory Integrated
Authentication. Access token could not be acquired.
get_user_name_failed: Failed to get user nameInner Exception : The
format of the specified domain name is invalidat
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.d__14.MoveNext()




Is it what I'm trying to do possible? If yes, what am I missing? Any thoughts will be appreciated.



For reference, this is the method returning the SQL connection:



private SqlConnection GetSqlConnection()
{
var accessToken = new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").Result;

return new SqlConnection
{
ConnectionString = WebConfigurationManager.ConnectionStrings["Default"].ConnectionString,
AccessToken = accessToken
};
}


... and this is the connection string:



  <connectionStrings>
<add name="Default" connectionString="Data Source=myserver.database.windows.net;Initial Catalog=MyDB;" providerName="System.Data.SqlClient" />
</connectionStrings>


Note: The local AD is been synchronized with its Azure AD counterpart.










share|improve this question

























  • Please try the steps provided on this article: colinsalmcorner.com/post/…

    – Alberto Morillo
    Nov 15 '18 at 14:40











  • AAD is enabled for the database already. My question is, once I connect to SQL and run "SELECT CURRENT_USER", am I going to get the App Service user or the original AD credentials for the user?

    – JCallico
    Nov 15 '18 at 16:48











  • Any process now? If you still have any problem, please feel free to let me know.

    – Joey Cai
    Nov 20 '18 at 7:20














0












0








0








An on-premise web application (.net 4.6.1) which uses Windows Authentication for its users and then AD Integrated Authentication to connect to a MS SQL database is been migrated to Azure.



Ideally, the existing security mechanism of granting permissions to AD users on database objects and let the DB be security source of the application should be kept.



A copy of the SQL database has already been created and configured.



If I run the web application locally but using the new Azure database everything works as expected.



If I run this command I get the expected AD user:



SELECT CURRENT_USER;


Now, when I deploy exactly the same application to an Azure App Service and enable Azure Active Directory Authentication and Managed Service Identity, the user is authenticated correctly on the Web application but it is not able to connect to the SQL database and the following error is returned:




Errors = System.Data.SqlClient.SqlErrorCollection ClientConnectionId =
e9f0c48a-3159-465c-ab72-c1da99761b8f Class = 14 LineNumber = 65536
Number = 18456 Procedure = Server =
xxxxxxxxxxx.tr4.canadacentral1-a.worker.database.windows.net,11057
State = 1 Source = .Net SqlClient Data Provider ErrorCode =
-2146232060 Message = Login failed for user 'NT AUTHORITYANONYMOUS LOGON'




If I disable Managed Service Identity, I get this error instead:




InnerExceptions =
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Exception]
Message = One or more errors occurred. Data =
System.Collections.ListDictionaryInternal InnerException =
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException:
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried the following 4 methods to get an access token, but
none of them worked. Parameters: Connection String: [No connection
string specified], Resource: https://database.windows.net/, Authority:
. Exception Message: Tried to get token using Managed Service
Identity. Unable to connect to the Managed Service Identity (MSI)
endpoint. Please check that you are running on an Azure resource that
has MSI setup. Parameters: Connection String: [No connection string
specified], Resource: https://database.windows.net/, Authority: .
Exception Message: Tried to get token using Visual Studio. Access
token could not be acquired. Visual Studio Token provider file not
found at
"D:localLocalAppData.IdentityServiceAzureServiceAuthtokenprovider.json"
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried to get token using Azure CLI. Access token could not be
acquired. 'az' is not recognized as an internal or external command,
operable program or batch file. Parameters: Connection String: [No
connection string specified], Resource: https://database.windows.net/,
Authority: https://login.microsoftonline.com/common. Exception
Message: Tried to get token using Active Directory Integrated
Authentication. Access token could not be acquired.
get_user_name_failed: Failed to get user nameInner Exception : The
format of the specified domain name is invalidat
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.d__14.MoveNext()




Is it what I'm trying to do possible? If yes, what am I missing? Any thoughts will be appreciated.



For reference, this is the method returning the SQL connection:



private SqlConnection GetSqlConnection()
{
var accessToken = new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").Result;

return new SqlConnection
{
ConnectionString = WebConfigurationManager.ConnectionStrings["Default"].ConnectionString,
AccessToken = accessToken
};
}


... and this is the connection string:



  <connectionStrings>
<add name="Default" connectionString="Data Source=myserver.database.windows.net;Initial Catalog=MyDB;" providerName="System.Data.SqlClient" />
</connectionStrings>


Note: The local AD is been synchronized with its Azure AD counterpart.










share|improve this question
















An on-premise web application (.net 4.6.1) which uses Windows Authentication for its users and then AD Integrated Authentication to connect to a MS SQL database is been migrated to Azure.



Ideally, the existing security mechanism of granting permissions to AD users on database objects and let the DB be security source of the application should be kept.



A copy of the SQL database has already been created and configured.



If I run the web application locally but using the new Azure database everything works as expected.



If I run this command I get the expected AD user:



SELECT CURRENT_USER;


Now, when I deploy exactly the same application to an Azure App Service and enable Azure Active Directory Authentication and Managed Service Identity, the user is authenticated correctly on the Web application but it is not able to connect to the SQL database and the following error is returned:




Errors = System.Data.SqlClient.SqlErrorCollection ClientConnectionId =
e9f0c48a-3159-465c-ab72-c1da99761b8f Class = 14 LineNumber = 65536
Number = 18456 Procedure = Server =
xxxxxxxxxxx.tr4.canadacentral1-a.worker.database.windows.net,11057
State = 1 Source = .Net SqlClient Data Provider ErrorCode =
-2146232060 Message = Login failed for user 'NT AUTHORITYANONYMOUS LOGON'




If I disable Managed Service Identity, I get this error instead:




InnerExceptions =
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Exception]
Message = One or more errors occurred. Data =
System.Collections.ListDictionaryInternal InnerException =
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException:
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried the following 4 methods to get an access token, but
none of them worked. Parameters: Connection String: [No connection
string specified], Resource: https://database.windows.net/, Authority:
. Exception Message: Tried to get token using Managed Service
Identity. Unable to connect to the Managed Service Identity (MSI)
endpoint. Please check that you are running on an Azure resource that
has MSI setup. Parameters: Connection String: [No connection string
specified], Resource: https://database.windows.net/, Authority: .
Exception Message: Tried to get token using Visual Studio. Access
token could not be acquired. Visual Studio Token provider file not
found at
"D:localLocalAppData.IdentityServiceAzureServiceAuthtokenprovider.json"
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried to get token using Azure CLI. Access token could not be
acquired. 'az' is not recognized as an internal or external command,
operable program or batch file. Parameters: Connection String: [No
connection string specified], Resource: https://database.windows.net/,
Authority: https://login.microsoftonline.com/common. Exception
Message: Tried to get token using Active Directory Integrated
Authentication. Access token could not be acquired.
get_user_name_failed: Failed to get user nameInner Exception : The
format of the specified domain name is invalidat
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.d__14.MoveNext()




Is it what I'm trying to do possible? If yes, what am I missing? Any thoughts will be appreciated.



For reference, this is the method returning the SQL connection:



private SqlConnection GetSqlConnection()
{
var accessToken = new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").Result;

return new SqlConnection
{
ConnectionString = WebConfigurationManager.ConnectionStrings["Default"].ConnectionString,
AccessToken = accessToken
};
}


... and this is the connection string:



  <connectionStrings>
<add name="Default" connectionString="Data Source=myserver.database.windows.net;Initial Catalog=MyDB;" providerName="System.Data.SqlClient" />
</connectionStrings>


Note: The local AD is been synchronized with its Azure AD counterpart.







azure-sql-database azure-active-directory azure-web-sites






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 13:12







JCallico

















asked Nov 15 '18 at 14:03









JCallicoJCallico

1,2321622




1,2321622













  • Please try the steps provided on this article: colinsalmcorner.com/post/…

    – Alberto Morillo
    Nov 15 '18 at 14:40











  • AAD is enabled for the database already. My question is, once I connect to SQL and run "SELECT CURRENT_USER", am I going to get the App Service user or the original AD credentials for the user?

    – JCallico
    Nov 15 '18 at 16:48











  • Any process now? If you still have any problem, please feel free to let me know.

    – Joey Cai
    Nov 20 '18 at 7:20



















  • Please try the steps provided on this article: colinsalmcorner.com/post/…

    – Alberto Morillo
    Nov 15 '18 at 14:40











  • AAD is enabled for the database already. My question is, once I connect to SQL and run "SELECT CURRENT_USER", am I going to get the App Service user or the original AD credentials for the user?

    – JCallico
    Nov 15 '18 at 16:48











  • Any process now? If you still have any problem, please feel free to let me know.

    – Joey Cai
    Nov 20 '18 at 7:20

















Please try the steps provided on this article: colinsalmcorner.com/post/…

– Alberto Morillo
Nov 15 '18 at 14:40





Please try the steps provided on this article: colinsalmcorner.com/post/…

– Alberto Morillo
Nov 15 '18 at 14:40













AAD is enabled for the database already. My question is, once I connect to SQL and run "SELECT CURRENT_USER", am I going to get the App Service user or the original AD credentials for the user?

– JCallico
Nov 15 '18 at 16:48





AAD is enabled for the database already. My question is, once I connect to SQL and run "SELECT CURRENT_USER", am I going to get the App Service user or the original AD credentials for the user?

– JCallico
Nov 15 '18 at 16:48













Any process now? If you still have any problem, please feel free to let me know.

– Joey Cai
Nov 20 '18 at 7:20





Any process now? If you still have any problem, please feel free to let me know.

– Joey Cai
Nov 20 '18 at 7:20












1 Answer
1






active

oldest

votes


















0














Once you deploy the application, please put your application settings and connection string to your webapp Application Settings option on Azure. Refer to this article.



enter image description here



Note: It has pulled the value from the App Settings configured in the Azure App Service’s – Application Settings blade but not from the Web.config file. This way, you can change these configurable values whenever you like to change without depending on developers. The same rule applies even for Connection String.






share|improve this answer
























  • @Joey-Cay thanks for taking the time of posting an answer. My issue is not related with not been able to read the connection string. The exception is thrown by the AzureServiceTokenProvider() class when can't find a viable method to get an access token to connect to the database.windows.net resource.

    – JCallico
    Nov 20 '18 at 13:16











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53321207%2fconnecting-to-azure-sql-from-app-service-using-aad-identity%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Once you deploy the application, please put your application settings and connection string to your webapp Application Settings option on Azure. Refer to this article.



enter image description here



Note: It has pulled the value from the App Settings configured in the Azure App Service’s – Application Settings blade but not from the Web.config file. This way, you can change these configurable values whenever you like to change without depending on developers. The same rule applies even for Connection String.






share|improve this answer
























  • @Joey-Cay thanks for taking the time of posting an answer. My issue is not related with not been able to read the connection string. The exception is thrown by the AzureServiceTokenProvider() class when can't find a viable method to get an access token to connect to the database.windows.net resource.

    – JCallico
    Nov 20 '18 at 13:16
















0














Once you deploy the application, please put your application settings and connection string to your webapp Application Settings option on Azure. Refer to this article.



enter image description here



Note: It has pulled the value from the App Settings configured in the Azure App Service’s – Application Settings blade but not from the Web.config file. This way, you can change these configurable values whenever you like to change without depending on developers. The same rule applies even for Connection String.






share|improve this answer
























  • @Joey-Cay thanks for taking the time of posting an answer. My issue is not related with not been able to read the connection string. The exception is thrown by the AzureServiceTokenProvider() class when can't find a viable method to get an access token to connect to the database.windows.net resource.

    – JCallico
    Nov 20 '18 at 13:16














0












0








0







Once you deploy the application, please put your application settings and connection string to your webapp Application Settings option on Azure. Refer to this article.



enter image description here



Note: It has pulled the value from the App Settings configured in the Azure App Service’s – Application Settings blade but not from the Web.config file. This way, you can change these configurable values whenever you like to change without depending on developers. The same rule applies even for Connection String.






share|improve this answer













Once you deploy the application, please put your application settings and connection string to your webapp Application Settings option on Azure. Refer to this article.



enter image description here



Note: It has pulled the value from the App Settings configured in the Azure App Service’s – Application Settings blade but not from the Web.config file. This way, you can change these configurable values whenever you like to change without depending on developers. The same rule applies even for Connection String.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 19 '18 at 7:02









Joey CaiJoey Cai

5,4451211




5,4451211













  • @Joey-Cay thanks for taking the time of posting an answer. My issue is not related with not been able to read the connection string. The exception is thrown by the AzureServiceTokenProvider() class when can't find a viable method to get an access token to connect to the database.windows.net resource.

    – JCallico
    Nov 20 '18 at 13:16



















  • @Joey-Cay thanks for taking the time of posting an answer. My issue is not related with not been able to read the connection string. The exception is thrown by the AzureServiceTokenProvider() class when can't find a viable method to get an access token to connect to the database.windows.net resource.

    – JCallico
    Nov 20 '18 at 13:16

















@Joey-Cay thanks for taking the time of posting an answer. My issue is not related with not been able to read the connection string. The exception is thrown by the AzureServiceTokenProvider() class when can't find a viable method to get an access token to connect to the database.windows.net resource.

– JCallico
Nov 20 '18 at 13:16





@Joey-Cay thanks for taking the time of posting an answer. My issue is not related with not been able to read the connection string. The exception is thrown by the AzureServiceTokenProvider() class when can't find a viable method to get an access token to connect to the database.windows.net resource.

– JCallico
Nov 20 '18 at 13:16




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53321207%2fconnecting-to-azure-sql-from-app-service-using-aad-identity%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Xamarin.iOS Cant Deploy on Iphone

Glorious Revolution

Dulmage-Mendelsohn matrix decomposition in Python