Get client OS username from SQL Server

yrdbyhpb  于 2023-06-28  发布在  SQL Server
关注(0)|答案(1)|浏览(98)

The requirement is to find which OS user logs in to a SQL Server database whenever the login is Windows Authentication or SQL Server authentication. Need to know WHO (AD account on the client PC) used which db account logged into SQL Server with what application.

The problem is I could not get the client's OS username when a SQL Server authentication user logs in.

For example, I used my AD account Domain name on a laptop, laptop123. Domain name is Stackoverflow , username is developer1 , started Microsoft SQL Server Management Studio, connected with DB account (SQL Server authentication) ERPAPPUSER . I need to record the domain user Stackoverflow/developer1 .

I can easily get the information that user ERPAPPUSER logged in from laptop123 using Microsoft SQL Server Management Studio.

I created a database logon trigger and could get the client username, hostname, logon time, application name and so on, but could not get the client OS username.

CREATE TRIGGER DB_ServerLogon
ON ALL SERVER 
WITH EXECUTE AS 'sa' 
FOR LOGON
AS
BEGIN
    INSERT INTO audit_history.dbo.db_logon_history
       SELECT 
           ORIGINAL_DB_NAME(), 
           ORIGINAL_LOGIN(),
           @@SPID,GETDATE(),
           HOST_NAME(),
           APP_NAME()
END
GO

Many thanks!

-- Added 'WITH EXECUTE AS 'as' ', otherwise for all users who don't have access to the db_logon_history will not be able to login.

mkshixfv

mkshixfv1#

Short answer is no, it is not possible.

Long answer:

SQL Server supports 2 security modes.

These are

  1. "Windows Authentication mode"
  2. "Mixed Mode" - which is "SQL Server and Windows Authentication Mode".

This second mode means that you can log in with a SQL Server login or a Windows Account. The Windows Account would be the same as in (a) above.

Now when you log in with Windows it is a trusted connection, so you have to have the Windows Account/Group authorized to access your SQL Server instance. The connection is authentication against a token which is created when the user logs in to windows.

This token is passed to SQL Server and can thus be parsed to return the information that you have described above.

However when you log on with SQL Server Mode you are not logging on with a domain account and thus no domain account is passed to SQL Server. Rather you log in with a SQL Server native account that is running in the context of the server. Now, you could be logging on with any sort of device, not just a windows client.

If you wish to pass the client details to SQL Server when using SQL Server mode, you have to pass it as a parameter from the front end. i.e. using a stored procedure or similar. (Good question by the way. and well asked.)

相关问题