Unable to connect to SQL Server 2019 localdb - sql-server

I'm part way through writing a .NET Core 3.1 Web API for a project. When I try to connect to the server, postman shows the following message:
Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open database "aspnet-53bc9b9d-9d6a-45d4-8429-2a2761773502" requested by the login. The login failed.
Login failed for user 'DESKTOP-RDBS4OR\Paul'.
I've looked around and the only things I can see are that I need to create a user for the db. I already have (the db uses the Windows Auth system) and the localdb has this user.
Looking at the throwback, I'm puzzled at the name of the DB - it's not the one in the connection string set in appsettings.json (below) or the referenced name win the StartUp class
"ConnectionStrings": {
"quizzical": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=quizzical;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
Something is obviously not right, but I don't know what it is.
This is my first API I've done in .NET (I usually use php), so any tips on fixing this are appreciated.

Related

IIS Connection IIS Basic User Settings Specific User Cannot Connect to SQL Server using Perl DBI

My Perl IIS web application is getting an SSL Error when the Perl DBI tries to connect to my MS SQL Server database version 11.0.7001 (that's what is listed in SQL Server Manager). The Perl application runs under IIS, and my IIS Basic User Settings Connection is set to Specific User (Domain Administrator).
The SQL Sever database resides on the same system as IIS. The distribution of Perl is Strawberry Perl; IIS' version is 8.5.9600.16384.
I can connect to the database using the SQL Server Manager locally on the server as well as remotely from my workstation. The connection type is SQL username and password. The IIS application listens on port 8085. The IIS permissions are not restricted, and there is no SQL server connection string as part of IIS.
The first page of the application loads, but this first page does not try to connect to the SQL Server database.
I have been looking at Stackoverflow posts -- like this one -- for a while, and have tried some of the suggestions like making a system DSN (which tests correctly), instead of a DSN string in Perl.
None of the suggestions have helped, and many but not all of the posts are dealing with security and certificates, not an application that is behind a firewall. In other words, I do not have security turned on.
To the best of my knowledge there is no security turned on for this application, and Named Pipes and TCP/IP were already turned on, as was suggested in one of the posts I read.
Here is the error:
[Microsoft][ODBC SQL Server Driver][DBMSLPCN]ConnectionOpen (SECCreateCredentials()). (SQL-01000) at ../../include/DbArgs.pm line 266.
DBI connect('driver={SQL Server};server=arlsql\arlsql;database=BuildingPermit;uid=user;pwd=pwd','',...) failed: [Microsoft][ODBC SQL Server Driver][DBMSLPCN]SSL Security error (SQL-08001) [state was 08001 now 01000]
Any suggestions on what to try next would be appreciated.
Edit 1/6/2020
I need to add that my C# client application using .Net ODBC objects successfully accesses the same database on which the web-based Perl DBI code fails. The username and password are the same for the client application as that used in the Perl CGI.
The IIS user for this application runs as the domain administrator, but when creating the DBI connection uses the same username and password. The database is set up for SQL username and password, and, as stated previously, there is no security set, at least that I can tell.
This does not answer the question but is instead a workaround. I consider the following a workaround, because I would still like to know why the DBI call failed with a specific user.
I switched my IIS Basic User Settings Connection from Specific User (Domain Administrator) to Application User (pass-through authentication).
After making this change and restarting IIS, the Perl DBI connection worked, but why?

SQL Server log in failing from Java DriverManager.getConnection(), working from Python with pymssql.connect()

I'm trying to use DriverManager.getConnection() to connect to a SQL Server db from a Java application, but I keep getting "Login failed for user" errors with it. I've tried using both com.microsoft.sqlserver.jdbc.SQLServerDriver and net.sourceforge.jtds.jdbc.Driver to connect, but both keep hitting the issue.
Here's the code I'm using to connect:
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://SERVERADDRESS:1433;DatabaseName=DBNAME;user=USER;password=PASS");
I know that account has access to that DB, as I've connected to it before from a Python application using pymssql.connect(SERVERADDRESS, USER, PASS, DBNAME) with the same server/DB/creds.
From this article, I eventually managed to get it working using windows authentication with my personal account, but I still can't get it to work using our service account. Does anyone have any insight into why the Python app can connect but the Java one can't?
pymssql is built on top of FreeTDS. Both FreeTDS and jTDS support an older Windows authentication scheme named NTLM, while current versions of Microsoft's JDBC Driver for SQL Server (mssql-jdbc) no longer support that authentication mechanism.
So, given that you've confirmed that pymssql can connect, you should be able to connect from your Java app as Windows user MYDOMAIN\username using jTDS like so:
String myUid = "username", myPwd = "mypassword";
String connUrl = "jdbc:jtds:sqlserver://192.168.1.123:1433/databasename;DOMAIN=MYDOMAIN";
Connection conn = DriverManager.getConnection(connUrl, myUid, myPwd);
To find out the reason of "Login failed for user" one should go to SQL Server error log.
The next row to 18456 error will give you the reason.
The most probably reason of failure in your case is that the server is configurated to use Windows Authentication only

Connecting database to MVC application - Error 50 Local database runtime error occurred

I am having a hard time in connecting my database to my MVC Application. I keep getting the following error, despite the recommendations that I have found online.
System.Data.SqlClient.SqlException: 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: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
Background situation:
I have developed an MVC Web App with User database, and I would like to publish them on another computer. After copying the files to the host computer, however, I was unable to access the SQL Server, with the following error message: Error 50 Local Database runtime error occurred.
The followings are the steps I have taken from the start of publishing process to the end:
I have created an MVC Web Application on my personal computer, with a user login authentication as described in Rick Anderson's example: http://www.asp.net/mvc/overview/security/aspnet-mvc-5-app-with-sms-and-email-two-factor-authentication. Therefore, with the Web App, I have a default user database created with it.
I then deployed the App to my own C:/inetpub, by using Visual Studio 2013. The publishing method is "File System". I understand that Database publishing is not supported for this publish method. So after the Web App was published, I created a folder named "App_Data" in my C:/inetpub/wwwroot, and copied my mdf and log database from my Project folder in VS2013 into it.
Afterwards, I opened up IIS7 on my computer and set my Default Website's physical property to C:/inetpub/wwwroot. I opened my web browser and I could connect to both the website and my databse (meaning I can login through the website, and it manages to authenticate my login id). So it was all good when the web app was running on my computer.
Next, I had to install the Web App to the host computer where it will be hosted.
So I copied the whole MVC Folder (C:/inetpub/wwwroot) and put it in the host computer's C:/inetpub/wwwroot. Then I did the following settings:
In the host computer, I gave IIS_IUSRS read/write access to the database.
I opened MSSQL 2014 SSMS, connected to Server: (LocalDb)\MSSQLLocalDB, and added a new database, i.e. the database.mdf in my C:/inetpub/wwwroot/App_Data. So my user database is registered in SSMS.
The connection string in my IIS was then changed to (LocalDb)\MSSQLLocalDB because I have MSSQL 2014 installed on the host computer.
<add connectionString="Server=(LocalDb)\MSSQLLocalDB;Database=aspnet-MvcPWy-20140708072924;Integrated Security=true" name="DefaultConnection" providerName="System.Data.SqlClient" />
ApplicationPool settings for IIS7 was following this example
<add name="DefaultAppPool">
<processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>
Despite all those configurations, however, I am still getting the same error. I would greatly appreciate if anyone could review my steps and see if I have made a mistake or missed some steps in setting this database. Thank you!

Visual Studio Web Config - Ignores SQL username password in connection string?

Background: I have created a basic entity framework repository pattern using code first. I then created a test project and the first unit test created was to test some basic repository calls against the database. Strangely, I noticed that entity framework was creating a database in my users\myusername directory!
After a bit of research I realized best practice would be for me to create a database for a bit of testing using SSMS with a defined username and password. I accomplished this, and also tested a created connection in Server Explorer within VS 2012, which succeeded. My connection string as is looks like:
<connectionStrings>
<add name="TestConnection" connectionString="Data Source=.\SQLEXPRESS;User ID=DevSqlUser;Password=devsql;Initial Catalog=TestDatabase;MultipleActiveResultSets=True;Integrated Security=False;" providerName="System.Data.SqlClient" />
</connectionStrings>
However, now when I run my test which should instantiate a repository using the connection string by name, I get a strange exception which is using my windows credentials! Why it is doing this? I have no clue. I do not have any identity impersonation in my web config.
System.Data.SqlClient.SqlException: Cannot open database "TestConnection" requested by the login. The login failed. Login failed for user '{domain}{myusername}'
Anyone know why it isn't using the user ID I specified in the connection string?
Looks like your SQL express is set for Windows authentication only. Take a look at authentication mode settings on your SQL database. If you are using windows authentication, there is no need to provide username and password. If you need to use a username and password, you can use mixed mode.
Connect to database from SSMS, right click on server and select properties. Under security, you can see authentication mode settings. Set that as per your needs.
The answer is embarrassing! Even though all the code for the classes is in the project I was testing for, the connection string had to be copied from the web.config into the app.config. Wow I feel like a dumbdumb what a rookie mistake.... lol I was churning on this for hours this morning!

MVC4 + SQL Server Express gives yellow screen with "login failed for user.." using known good credentials

I have been tasked with deploying an application that has been successfully running in a development environment to a staging environment. After deploying the published files and configuring IIS, I can see the inital login screen, as expected. However, when I try and log in, I get:
Cannot open database "db1" requested by the login. The login failed.
Login failed for user 'user1'.
The setup contains these pieces:
Windows Web Server 2008 R2,
SQL Server Express 2008 R2,
IIS 7,
ASP.NET MVC4, and
Entity Framework 4.4
Googling turned up no sucessful leads - answers posted here and elsewhere were all concerned with either the credentials ultimately being incorrect or dual-mode authentication not being enabled in server properties.
I see dual-mode authentication enabled in server properties, and I can confirm this by logging in with either SQL Server or Windows authentication in SSMS. This also confirms to me that the credentials are good and accepted by the server. (Please correct me if I'm wrong in thinking this)
SQL Server, IIS, and the browser I'm testing with are all running on the same machine.
Here is my connection string: (with internal info substituted out)
<add name="app1Entities" connectionString="metadata=res://*/app1.csdl|res://*/app1.ssdl|res://*/app1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SQLEXPRESS;initial catalog=db1;user id=user1;password=pass1;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I found the resolution. It was ultimately a permissions issue.
This question got me on the right track:
SQL Server: Cannot open database requested by the login
Examining the server logs showed:
"Failed to open the explicitly specified database", then
"Error 18456, Severity: 14, State: 38"
Google revealed that state 38 means a permissions problem. This particular user had the 'public' server permission and the 'db_datareader' and 'db_datawriter' permissions on the database already so I deleted and remade the user on the database, which fixed the issue.
EDIT:
This was happening to me every time I restored the database. Apparently SQL server gets confused about users on restore. The fix is to execute this:
EXEC sp_change_users_login UPDATE_ONE, 'username_of_user', 'username_of_user';
After a restore, which fixes the issue entirely.

Resources