SQL Server c# connection string not working with user domian

46scxncf  于 2023-05-05  发布在  C#
关注(0)|答案(2)|浏览(149)

For some reason this connection string is working with node js and this is an application user:

var http = require("http");

const sql = require("mssql");

const port =3333;

sql.connect('Server=B-SG-SQ;Database=DevTest;User Id=sg\\DevtestB;Password=DevtestB123;Encrypt=true;trustServerCertificate=true')
.then((conn) => {
  console.log(conn);
console.log("MSSQL: connected");

conn.query(`select * from samples`)
.then(data => console.log(data))
.then(() => conn.close())
}).catch(err => { console.log("err " + err) });

And I can see the list of objects from my table.

But when I try it with an ASP.NET Core 7 Web API:

public class DataContext
{
    private readonly DbSettings _dbSettings;

    public DataContext(IOptions<DbSettings> dbSettings)
    {
        _dbSettings = dbSettings.Value;
    }

    public IDbConnection CreateConnection()
    {
        var connectionString = "Server=B-SG-SQ;Database=DevTest;User Id=sg\\DevtestB;Password=DevtestB123;Encrypt=true;TrustServerCertificate=true";
        return new SqlConnection(connectionString);
    }
}

This is the result that I see:

Login failed for user 'sg\DevtestB'

ql3eal8s

ql3eal8s1#

when you use user domain ,you didn't need to use password sample connection string:

Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ProductDB;Data Source=.

you can Test connection with udl file

Test Test connection: Test connection with udl

nzk0hqpo

nzk0hqpo2#

Impersonation Middleware in an Asp.Net Core Intranet app for Windows-Identity

and https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=net-7.0

It worked. But i had to change the code in the middleware to:

var domainName = IPGlobalProperties.GetPGlobalProperties().DomainName;

const int LOGON32_PROVIDER_DEFAULT = 0;  
        //This parameter causes LogonUser to create a primary token.   
        const int LOGON32_LOGON_INTERACTIVE = 9;  

        // Call LogonUser to obtain a handle to an access token.   
        SafeAccessTokenHandle safeAccessTokenHandle;  
        bool returnValue = LogonUser(userName, domainName, password,  
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,  
            out safeAccessTokenHandle);

 await WindowsIdentity.RunImpersonatedAsync(safeAccessTokenHandle, async () => await _next.Invoke(context));

相关问题