WSTrust error using .NET framework 4.8 to connect to Azure SQL using Active Directory Password - azure-active-directory

I have a console application that uses .NET Framework 4.8, and I need it to connect to an Azure SQL database, I have simplified the issue to the following sample:
using(var con = new SqlConnection(myConnectionString)) {
con.Open();
// ...
}
...where the connection string takes the form:
Server=MyDbAddressHere;Initial Catalog=MyDbName;Persist Security Info=False;User ID=MyUsername;Password=MyPassword;MultipleActiveResultSets=False;Encrypt=True;TrueServerCertificate=False;Authentication=Active Directory Password;
I am getting an exception when opening the connection:
AdalException: WSTrust response does not have recognized SAML assertion.
I'm not sure how to interpret the error I'm getting, and how to go about fixing it so I can connect to the database and use it.

Changing the password solved the problem; apparently it had something to do with the account recently having been changed to no longer require MFA.

Related

Unable to connect to SQL Server 2019 localdb

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.

ASP.NET MVC Connect to DSN with limited access

I have a database on which I have very limited access. I need to get some data from a VIEW from a database. I have a generic Windows account and I can only login if I Shift+Click on Sql Server Studio and open as different user and use the default Windows Authentication(No Sql Server Authentication Works). I created some DNSs but I can only login with the default Windows NT authentication and SQL Server. The problem is, when I use the Windows NT I get the error:
[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user
'DOMAIN\SERVERNAME'. ERROR [28000]
My Code:
try
{
OdbcConnection cn;
OdbcCommand cmd;
string MyString;
MyString = "Select * from users";
cn = new OdbcConnection("dsn=DB77;UID=****;PWD=****;");
cmd = new OdbcCommand(MyString, cn);
cn.Open();
cn.Close();
}
catch(Exception e)
{
return e.ToString();
}
I want to use a Windows Authentication to get data from the db. Is it something wrong in Code, ODBC Data Source Admin, IIS?
I personally use NHibernate with MVC. Originally I picked it up because our database doesn't support EF but enjoy it enough that even if we moved to SQL Server I'd keep NHibernate.
The learning curve is kinda weird. It is definitely steep to become an expert, but it is interesting in that it is pretty organic to let it handle more and more of the work for you as you get comfortable with certain layers.
So for your case NHibernate probably supports your database, can be used as a simple data access layer (just returning DTOs), provides a database agnostic interface and can support SQL Server when the time comes. If you end up wanting more out of NHibernate it is there when the time comes.
nHibernate doesn't have anything to do with Windows Authentication. SQL server will use your process identity to authenticate
if configured to use windows authentication. What that means is that if your application is a web app, you'll need to ensure that your
application runs under the windows identity that can be authenticated by SQL Server.
And it's not possible to provide windows credentials via database connection string, unfortunately.
Example of connection string when using windows authentication:
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
Impersonation:
http://msdn.microsoft.com/en-us/library/xh507fc5.aspx

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

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!

SqlServer: Login failed for user

I've written a very simple JDBC login test program. And after all kinds of problems I've almost got it working. Almost, just can't seem to get past this problem:
SQLServerException: Login failed for user xxxxx
I created a simple database PersonInfo then I created user user1 password1 (SQL authentication). And after trying everything was unable to connect to the database.
I am using SqlServer2008 on Win 7, I've got the latest JDBC driver from Microsoft.
My code is:
import java.sql.*;
public class hell {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn= DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=PersonInfo;user=Sohaib;password=0000;");
System.out.println("connected");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here's the Exception
Exception: Unable to get connect
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'Sohaib'.
and all other supporting errors.
Is your SQL Server in 'mixed mode authentication' ? This is necessary to login with a SQL server account instead of a Windows login.
You can verify this by checking the properties of the server and then SECURITY, it should be in 'SQL Server and Windows Authentication Mode'
This problem occurs if the user tries to log in with credentials that cannot be validated. This problem can occur in the following scenarios:
Scenario 1: The login may be a SQL Server login but the server only accepts Windows Authentication.
Scenario 2: You are trying to connect by using SQL Server Authentication but the login used does not exist on SQL Server.
Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal. An unrecognized Windows principal means that Windows can't verify the login. This might be because the Windows login is from an untrusted domain.
It's also possible the user put in incorrect information.
http://support.microsoft.com/kb/555332
In my case, I had to activate the option "SQL Server and Windows Authentication mode", follow all steps below:
1 - Right-click on your server
2 - Go to option Security
3 - Check the option "SQL Server and Windows Authentication mode"
4 - Click on the Ok button
5 - Restart your SQL Express Service ("Windows Key" on the keyboard and write "Services", and then Enter key)
After that, I could log in with user and password
I ran into the same issue, and I fixed it by adding my windows username to SQL and then to my server, here is how I did:
First, create a new login with your Windows username:
Click Search, then type your name in the box and click check names.
Then add your that user to the server:
Right click on the Server > Permissions > Search > Browse > Select your user
(You will notice that now the user you created is available in the list)
I hope it helps ;-)
We got this error when reusing the ConnectionString from EntityFramework connection. We have Username and Password in the connection string but didn't specify
"Persist Security Info=True".
Thus, the credentials were removed from the connection string after establishing the connection (so we reused an incomplete connection string). Of course, we always have to think twice when using this setting, but in this particular case, it was ok.
I got the same error message when trying to connect to my SQL DB in Azure (using sql-cli). The simple solution was to escape the password with single quotes like this:
mssql -s server.database.windows.net -u user#server -p 'your_password' -d your_db -e
Also make sure that account is not locked out in user properties "Status" tab
For Can not connect to the SQL Server. The original error is: Login failed for user 'username'. error, port requirements on MSSQL server side need to be fulfilled.
There are other ports beyond default port 1433 needed to be configured on Windows Firewall.
https://stackoverflow.com/a/25147251/1608670
We solved our Linux/php hook to SQL Server problem by creating a new login account with SQL Server authentication instead of Windows authentication.
Just in case any one else is using creating test users with their automation....
We had this same error and it was because we had recreated the user (as part of the test process). This caused the underlying SID to change which meant that SQL couldn't properly authenticate the user.
We fixed it by adding a drop login command to our testing scripts to ensure that a previously created user (with the same user name) was no longer present on the instance.
I faced with same problem. I've used Entity Framework and thought that DB will be created automatically. Please make sure your DB exists and has a correct name.
In my case I have configured as below in my springboot application.properties file then I am able to connect to the sqlserver database using service account:
url=jdbc:sqlserver://SERVER_NAME:PORT_NUMBER;databaseName=DATABASE_NAME;sendStringParametersAsUnicode=false;multiSubnetFailover=true;integratedSecurity=true
jdbcUrl=${url}
username=YourDomain\\$SERVICE-ACCOUNT-USER-NAME
password=
hikari.connection-timeout=60000
hikari.maximum-pool-size=5
driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
try using this connection string
Server=ServerName;Database=DbName;Trusted_Connection=SSPI;MultipleActiveResultSets=true;TrustServerCertificate=true
If you are using Windows Authentication, make sure to log-in to Windows at least once with that user.
Previously I was using the Windows Authentication without problems, then occurred me the error below.
"Failed to generate SSPI context."
Witch I resolve by changing my connection string from
Server=127.0.0.1;Database=[DB_NAME];Trusted_Connection=True;
to
Server=127.0.0.1;Database=[DB_NAME];Trusted_Connection=False;
Then the next error occurred me
"Login failed for user ''."
To solve this problem I used the sa user. Access the sa user to update de password if you need (on the SQL server Security > Logins > sa (right click) > Properties > General)) and then update the connection string to..
Server=127.0.0.1;Database=[DB_NAME];User Id=sa;Password=[YOUR_PASSWORD]
You can use another user of your choice.

Resources