I am trying to connect to a MS SQL Server database from my NodeJS server application and while it works flawlessly on my local machine using localhost/127.0.0.1 when I push it to a real server I get an Auth error.
The error I am getting is as follows:
The login is from an untrusted domain and cannot be used with Windows
authentication
So I am thinking that maybe its different domains but my domains are as follows:
000001.mysubdomain.mydomain.com
ct000002.mysubdomain.mydomain.com
So I'm not a networking guy but I would assume that in this case both the MS SQL Server and my NodeJS Server are actually on the same domain, am I correct in assuming that or incorrect?
Some more info - in both cases the IP addresses share the same first number but the rest are different - SS.XX.XX.XX - Where SS is the same numbers and XX are different - does this suggest that they are in fact on different domains?
In addition to this if it was a domain issue then why would it work on my local machine?
So if we can eliminate that it is not a domain issue then I'm not sure where to go, here is my code, I am using the Tedious-NTLM NodeJS module - https://www.npmjs.com/package/tedious-ntlm
var tds = require("tedious-ntlm"); //Get the tedious model for NTLM connection to the SQL Server
//Set up config for logging into the DB
var config = {
userName: 'myusername', //Username
domainName: "mydomain", //Domain
password: 'mypassword', //Password
server: '000001.mysubdomain.mydomain.com' //Database address
};
function getDataFromSQLServer(callback){
var connection = new tds.Connection(config); //Configure a connection
//When the database is connected to we get this event
connection.on('connect', function(err) {
// If no error, then good to go...
if(err){
console.log('err = ' + err); //Log the error to the console
}
else{
executeStatement(callback); //Execute the test statement
}
}
);
As you can see here when my function is called I log an error, I get an error here when trying to run the code from my server but I have no issue when running it from my local machine.
To get more information on the error I have the following code:
connection.on('errorMessage', function(err){
console.log('full error = ' + JSON.stringify(err)); //Log the error to the console
});
Which gives me the following info:
full error = {"number":18452,"state":1,"class":14,"message":"Login
failed. The login is from an untrusted domain and cannot be used with
Windows
authentication.","serverName":"000001","procName":"","lineNumber":1,"name":"ERROR","event":"errorMessage"}
Again if run on my local machine everything works correctly but if I run from my server I get the errors, I am wondering if this really is a domain issue or if the error message is incorrect and there is something else wrong?
Related
I'm trying to implement an application that connects to online database using API. I've created a server and a database on freesqldatabase.com with the credentials of a sort
Host: sql7.freesqldatabase.com
Database name: sql12345678
Database user: sql12345678
Database password: passwordqwertyasdfgh
Port number: 3306
Now I'm trying to connect to the database using a postman. In the url I have sql7.freesqldatabase.com/sql12345678/nameOfATable,
data as a json file:
{
"id" : 1,
"login" :"user",
"password" : "12345",
"data" : "RandomData"
}
In Auth I've also entered the username and password provided above for a basic authentification. However, when I'm trying to connect using POST / GET methods of postman, it always fails with "Request timed out". If I change the url by inserting a port number, Postman doesn't send it neither. Where could be the problem? If the server is not accessible, is possible to make it accessible using phpadmin.co? I have the access to the server / database there through phpadmin.co.
Note that the data and the types of variables are correct, so I don't think the problem is there. Anyway, I'd be glad for any help provided.
I want to query an Azure SQL Database from an Azure Function executing on my machine in debug using Managed Identities (i.e. the identity of my user connected to Visual Studio instead of providing UserId and Password in my connection string).
I followed this tutorial on Microsoft documentation so my Azure SQL Server has an AD user as admin which allowed me to give rights (db_datareader) to an Azure AD group I created with my Azure Function Identity and my user in it (and also my Function App deployed in Azure).
If I deploy and run in Azure my Azure Function, it is able to query my database and everything is working fine. But when I run my Azure Function locally, I have the following error :
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
The code of my function is the following:
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "test")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
using (var connection = new SqlConnection(Environment.GetEnvironmentVariable("sqlConnectionString")))
{
connection.AccessToken = await (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net");
log.LogInformation($"Access token : {connection.AccessToken}");
try
{
await connection.OpenAsync();
var rows = await connection.QueryAsync<Test>("select top 10 * from TestTable");
return new OkObjectResult(rows);
}
catch (Exception e)
{
throw e;
}
}
}
The code retrieves a token correctly, the error occurs on line await connection.OpenAsync().
If I open the database in Azure Data Studio with the same user than the one connected to Visual Studio (which is member of the AD group with the rights on the database), I can connect and query the database without any issue.
Is it a known issue or am I missing something here ?
After trying your specific scenario, I tested quite a few ways to try and get it to work locally. This didn't work, giving the same error message you're getting.
I discussed it with some people, when a possible solution came up. I tested it: it works!
The main issue in my case was that my subscription (and my user) is a Microsoft account (Outlook). Because of this, you need to specify the tenantId in the GetAccessTokenAsync() call.
Apparently, for managed identities you do not have to specify the tenantId. With a user, it's a good idea to explicitly specify it. In case of a personal MS account, specifying it is mandatory.
My code (sort of):
var tokenProvider = new AzureServiceTokenProvider();
using (var connection = new SqlConnection(CONNECTIONSTRING))
using (var command = new SqlCommand(QUERY, connection))
{
connection.AccessToken = await tokenProvider.GetAccessTokenAsync("https://database.windows.net/", "<YOUR_TENANT_ID>");
await connection.OpenAsync();
var result = (await command.ExecuteScalarAsync()).ToString();
return new OkObjectResult(result);
}
This solution has been tested and works both when specifying the tenantId (or Directory ID, the tenant's GUID) and the 'onmicrosoft'-name (xxx.onmicrosoft.com).
Is your local machine's IP Address white-listed?
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-firewall-configure
I'm deploying a web application using IIS and ASP.NET CORE.
I setup a "appsetting.json" file that include a connection string to sql server.
So far, any variation I've tried didn't work.
The strange thing about it, is that it works perfectly on a my local machine, but when I deploy it and send an HTTPPost, log file says there's an error using connection to database on server.
Well, I tried all variations I could think of.
Current connection string generated by Visual Studio is :
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Swap;Integrated
Security=True;Connect Timeout=30;Encrypt=False;
TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
I've tried changing the "Integrated Security" to False.
I've tried to replace it with User ID and password (of "sa" user).
I've tried adding a "Initial Catalog" property and set it to my database.
I'm preety sure the startup of the app is fine, because when I try to send a GET request to the main page, everything seems fine.
When I send a POST request and asks the DBcontext to Add and SaveChanges, it shows this error :
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'Swap' on server
'(localdb)\MSSQLLocalDB'.
This is the function that I tried to send a HTTPPost request to:
byte[] j = new byte[(int)Request.ContentLength];
Request.Body.Read(j, 0, (int)Request.ContentLength);
string str = Encoding.ASCII.GetString(j);
TokenSet tokenSet = new TokenSet {Token = str };
sqlTokensetData.Add<TokenSet>(tokenSet);
sqlTokensetData.SaveChanges();
HttpClient notificationSender = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
"https://fcm.googleapis.com/fcm/send");
request.Headers.TryAddWithoutValidation("Authorization", "key="
<somekey>);
request.Headers.TryAddWithoutValidation("Sender", "id=<id>");
Message pushNotification = new Message(new string[] { str }, "Success!"
<somestring>);
request.Content = new
StringContent(JsonConvert.SerializeObject(pushNotification)
,Encoding.UTF8,"application/json");
HttpResponseMessage output = await notificationSender.SendAsync(request);
Log file error:
https://anotepad.com/notes/9a8jxa
I hope that the "str" string will be inserted to the database.
Thank you.
Well, Basicly, Thanks to the comments above I've managed to solve it.
What you need to do if you come by the same error:
1.Download SQL Server Express -
https://www.microsoft.com/en-us/sql-server/sql-server-editions-express as said above.
and configure the SQL Server however you see fit.
2.Configure sa user, set password and enable it.
3. If SQL Authentication doesn't work, then in Microsoft SQL Server Management Studio -> Right-click the server -> Properties -> Server Authentication -> Change to SQL Server and Windows Authentication
4. Change connection string to :
Data Source=;Initial Catalog=User ID=sa;
Password=;
Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
It worked for me.
I need to query an on-premises SQL Server Express database from my Azure app service based on Nodejs. I followed this tutorial to add a hybrid connection.
I successfully connected and added this connection to my service. I also added the connection string as:
Server=LOCALHOST\\SQLEXPRESS,1433;Database=smartpointmovil_db;User ID=sa;Password=pass1009
Then, I wrote an easy api in node JS for my azure mobile app service:
"get": function (req, res, next) {
var sql = require("mssql");
var config = {
server: 'LOCALHOST\\SQLEXPRESS',
user: 'sa',
password: 'pass1009',
database: 'smartpointmovil_db',
port: 1433
};
var conn = new sql.Connection(config);
var req=new sql.Request(conn);
conn.connect(function(err){
if(err){
console.log("Error connectig: "+err);
return;
}
req.query('select * from smartpointmovil.cat_cadenas where id=1',function(err,results){
if(err){
console.log("Error during query: "+err);
return;
}
else{
console.log("Success: "+results[0].cadena);
res.json(results[0]);
}
conn.close();
});
});
}
Every time I call this API, I get the following error message:
Error connectig: ConnectionError: Failed to connect to
LOCALHOST:undefined in 15000ms
I did not find the way to define in my code the connection string to be used for the query, so I am including the configuration parameters.
Any idea how to write a node js code to query my local database from an Azure hosted service?
Use the hostname (Computer Name) of your on-prem server when defining the Hybrid Connection. Then use the same name to reference that machine in your App Service code.
e.g.
Server=SQL-SRV-01\SQLEXPRESS,1433; [...]
Hybrid Connections work by hooking the getaddrinfo system call, and it's probably unable to tell apart your LOCALHOST from the actual LOCALHOST (127.0.0.1) of the VM that App Service runs on top of.
Test with sqlcmd.exe from the Kudu Console:
D:\home>sqlcmd -S tcp:SQL-SRV-01,1433 -U {username} -P {password}
-Q "SELECT NAME FROM sys.sysdatabases"
NAME
-------------------
master
MobileServiceZZZ_db
(2 rows affected)
I got it working, these are the changes I did in my code to make it work:
Changed from server name from 'LOCALHOST' to my server host name: 'quandojhv' which is the same name used as host name in the hybrid connection.
I removed the instance name '\SQLEXPRESS' in the server configuration parameter.
New configuration parameters in my code are:
var config = {
server: 'quandojhv',
user: 'sa',
password: 'pass1009',
database: 'smartpointmovil_db',
options: {
encrypt: true
}};
I followed the example on this website to implement a GCM server using CCS. However the code has exception when it tries to connect to the gcm server (last line in the code below):
ConnectionConfiguration config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT);
config.setSecurityMode(SecurityMode.enabled);
config.setReconnectionAllowed(true);
config.setRosterLoadedAtLogin(false);
config.setSendPresence(false);
config.setSocketFactory(SSLSocketFactory.getDefault());
connection = new XMPPTCPConnection(config);
connection.connect();
I looked up online and someone said I needed to enable billing for my app on appengine in order to use GCM server. I did so but it still does not work. I keep seeing the following error:
gcm.googleapis.com:5235 Exception: Permission denied: Attempt to
access a blocked recipient without permission. (mapped-IPv4)
Am I missing something?