Not able to get Azure Key-Vault working in app when deployed to Azure - azure-keyvault

I have created an app using MVC.net 4.7.2 application to use Key Vault secret for connection string. For some reason it is not working when deploying to the Azure. Below are the steps. Please suggest the solution based on .net not .net core.
I have created a MVC.net 4.7.2 application. Implemented Azure AD Authentication and tested my app, it is working fine no issue.
Then I created a Key Vault secret for the database connection string. And give permission to my app from the Key Vault->Access Policy
On the application level. Used the Connected Service to access the Key Vault-> Secret for connection string. That added the code in webconfig and added nuget packages. See the code below.
Run the code locally which has no connection string and I was able to get the data. It worked perfectly without any issue. I was also able to determined that app is picking up Key Vault secret for connection string.
Deployed the app to the Azure app service.
Ran the application but I did not get the data however see the error as if the connection string is not provided.
Error
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found
or was not accessible. Verify that the instance name is correct
and that SQL Server is configured to allow remote connections.
(provider: TCP Provider,
error
What is it that I suppose to do or check in order for it to work. Note that locally, I am able to get the data with the code that I have in my webconfig. So seem like there is no issue. And also I have Azure AD identification working.
Web Config code:
<configSections><section name="configBuilders"
type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f22d50a3a"
restartOnExternalChanges="false"
requirePermission="false" />
<builders>
<add name="AzureKeyVault" vaultName="Prod-ConSt-01"type" Microsoft
.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Azure,
Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31bf9256ad364e35"
vaultUri="https://mywebsite-prod-const-01.vault.azure.net/" /><
/builders>
</configBuilders>
<connectionStrings configBuilders="AzureKeyVault">
<add name="ProductionConnstr" connectionString="from key vault"
providerName="System.Data.SqlClient" />
</connectionStrings>

This isn't a Key Vault problem - it seems that it's accessing the Key Vault just fine since it is trying to contact the database. Check your allowed IP range to allow your website to contact the database.

Related

Connection string problem when deploying ASP.NET MVC website to PLESK

I'm going through a basic tutorial for ASP.NET MVC based on this Microsoft Help document. The app displays books and authors from a database and allows for CRUD operations on that data. Everything is working fine on my machine when I run locally developing with Visual Studio 2017. But when I try to to deploy to my PLESK hosted website I'm having problems. I recreated (from scratch) a MySQL database designed to exactly replicate the schema of local database and populated it with sample values. When the page loads, I'm getting a long hang and ultimately a 500 error after it tries unsuccessfully to connect to the database.
This is the connection string that is working locally:
<add name="BookServiceContext" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=BookServiceContext-20200803155333; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|BookServiceContext-20200803155333.mdf" providerName="System.Data.SqlClient" />
And here's the connectionStrings part of the remote web.config:
<add name="BookServiceContext" connectionString="Server=###.##.###.##;Database=BookServiceContext;Uid=myPLESKUserIDAssociatedWithDatabase;Pwd=PasswordForTheUser;multipleactiveresultsets=True" providerName="System.Data.SqlClient" />
Perhaps I have the syntax wrong or am missing a setting in PLESK (I was trying to use a sample from ConnectionStrings.com and haven't set up a DB in PLESK before).

Requesting to controller throws 500 Internal error when deployed to azure

I am deploying a web service on AZURE. In AZURE, i have a MYSQL db and i have fed its connection string to the web.config file. Its all working fine in the local environment. But when i deploy it to AZURE, controller don't work. Here are the screenshots of local and remote working scenarios. Also i have traced the remote log file of that request in the screenshot.
Here is the log file of this error (500)
While surfing through the internet, i came across a lot of solutions like using identity, to change authorization to none and so on. I am very confused right now as its been 2 days and i am still stuck in it. Right guidance will be highly appreciated.
I have found a solution to this problem. The problem was simple. As i added the reference of mysql.data.dll in the project, i forgot to add it inside my bin folder (by checking copylocal=true).
After that i updated the web.config file by adding these markups in the <system.web></system.web>Tags.
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.8.3, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
I also enabled custom errors="off", in this way i was able to get production level errors on the deployed code. `

A network-releated or instance-specific error occurred while establishing a connection to SQL Server

I have a simple mvc web site (using the VS internet template) on azurewebsites talking to a SQL Azure database in the same data center. The database at this time is just to do the built-in SimpleMembership Provider. I have already switched from the default App_Data mdf file to Azure SQL. It works fine, but sometimes after a while, it would give:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
with a long message:
SQLExpress database file auto-creation error:
The connection string specifies a local Sql Server Express instance
using a database location within the application's App_Data directory.
The provider attempted to automatically create the application
services database because the provider determined that the database
does not exist. The following configuration requirements are necessary
to successfully check for existence of the application services
database and automatically create the application services database:
But I do not have a connection string using SQL Server Express!
Restarting the web site immediately does not remove the error.
Without changing anything and restarting the web site 15 minutes later give:
502 - Web server received an invalid response while acting as a
gateway or proxy server.
There is a problem with the page you are looking for, and it cannot be
displayed. When the Web server (while acting as a gateway or proxy)
contacted the upstream content server, it received an invalid response
from the content server.
Previously, I could restore the website back to working order by just re-publshing from VS. But for the last hour I have tried and tried and I cannot get the web site to work again.
What is the problem about SQL Server Express really about?
My connection string section contains:
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=tcp:sabl6h4---.database.windows.net,1433;Database=MVC;User ID=test#sabl6h4---;Password=----;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
<add name="Entities" connectionString="metadata=res://*/Data.Model1.csdl|res://*/Data.Model1.ssdl|res://*/Data.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=sabl6h4---.database.windows.net;initial catalog=MVC;user id=test;password=----;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Just to be sure, I copied and pasted sabl6h4---.database.windows.net into SSMS and connected using login test and it opened the database without problem.
One day later: I created a new azurewebsite and published the exact same project and same web.config. It works fine without problems. After some minutes, the exact same error occurred!
Three more hours later: Went for lunch, came back, hit the browser Refresh button, and the web site is up again. I am convinced that someone is fooling around with the settings at the back end.
Add a <clear/> element as the first element under the connectionstrings element to ensure no strings are being inherited. Also, I assume your Azure SQL DB is set up with proper firewall settings allowing your IP where the ASP.net code is deployed?
I also had this error. But in my case I did not notice that the connection string was being overwritten by the publish wizard. I fixed the problem by going to the Settings tab in the Publish wizard and unchecking "Use this connection string at runtime (update destination web.config)"

MVC 4 Entity Framework Web config

I have an application which connects to our SQL Server 2008 enterprise.
My config file contains:
name="patbase" connectionString="Data Source=pbsqlserver1;Initial Catalog=patentbase;Trusted_Connection=True;;Application Name=PatBase Images;" providerName="System.Data.SqlClient"
When I test it from my PC it works.
When I publish it to the (internal) server I can see my user has logged into asp.net but data base access gives me:
An error occurred while getting provider information from the
database. This can be caused by Entity Framework using an incorrect
connection string. Check the inner exceptions for details and ensure
that the connection string is correct.
Your connection string is using a "trusted connection" which means the identity of the client process/thread is used in the SQL login attempt. You say that your user has logged in to the ASP.NET app, but what is the identity of the application pool your app runs in?
You don't say what kind of authentication your app uses, but I'm going to assume Windows Authentication. If you want the end-user's account to be used for the SQL login, you will need to enable ASP.NET impersonation for your app. You can do this under "Authentication" in the IIS Manager, or in your web.config with <identity impersonate="true" />
If you don't care which identity is used for the SQL login attempt, you can create a SQL login for your application pool's identity.
try to see if SSPI security works
<connectionStrings>
<add name="patbase" connectionString="Data Source=pbsqlserver1;Initial Catalog=patentbase;Integrated Security=SSPI;;Application Name=PatBase Images" providerName="System.Data.SqlClient"/>
</connectionStrings>
or remove the ;;Application Name=PatBase Images at the end if that doesn't work.

Receiving an error doing code first MVC web deployment

I have set up a remote server running SQl Server Web edition and full IIS 7.5. I am able to deploy my MVC 4 application to the remote box without issue, but when I try to run the website I receive the following error:
Login failed for user 'IIS APPPOOL\backoffice.mysite.com'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'IIS APPPOOL\backoffice.mysite.com'.
The Error Console says:
Exception information:
Exception type: InvalidOperationException
Exception message: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588
at MyModels.Filters.InitializeSimpleMembershipAttribute.SimpleMembershipInitializer..ctor() in c:\Users\Administrator\Documents\MySite\MyModels\Filters\InitializeSimpleMembershipAttribute.cs:line 47
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
It is very possible that my connection string is incorrect as the error log suggests. My connection running locally in Visual Studio is:
<add name="MyDB" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MyDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MyDB.mdf" providerName="System.Data.SqlClient" />
I have set up a transformation for the connection on the remote server as:
<add name="MyDB" connectionString="Data Source=(local);Initial Catalog=MyDb;Integrated Security=True" providerName="System.Data.SqlClient" />
Normally I use SQL login so I am confused here. What should the connection string look for SQL Server Web Edition using Windows Authentication?
It looks like the IIS APPPOOL\backoffice.mysite.com is the trying to create the DB. Is this correct? If so do I not need to create a login and user for this user in SQL Management Studio?
Do I need to create the DB in SQL Management Studio before running the deployment?
Thank so much!
you are running using Windows Authentintication for SQL Server. The IIS App is running under the user context of 'IIS APPPOOL\backoffice.mysite.com'; I would strongly suggest using either standard sql server credentials or creating a new user for that particular website that has sql credentials, probably better with regular credentials though. Integrated Security=SSPI in the connection string means Windows Authentication. So just use standard SQL Server credentials and set your database to mixed mode auth and set the User ID and Password in your connection string and then you will be up and running no problem.

Resources