A question I get from Oracle DBAs who also look after SQL Server: an ODBC connection can use a user ID and password, or a trusted connection. With a trusted connection, who am I connected as? And can a query show that name?
What a trusted connection is
A trusted connection is Windows Authentication. SQL Server does not get a user name and password from the ODBC settings. Instead, Windows passes along the identity of the process that opens the connection, using Kerberos or NTLM. Any user ID typed into the ODBC data source is ignored.
Usually that is the person logged in to the machine, but not always:
- A program running as a Windows service or scheduled task connects as that service account, for example
DOMAIN\svc_reports. - A program started with Run as different user connects as that user.
- A web application in IIS connects as its application pool account, unless it is set up to pass on the browser user's identity.
The query: who am I?
SELECT SUSER_SNAME() AS login_name, -- DOMAIN\username for a trusted connection
ORIGINAL_LOGIN() AS original_login, -- the real login, even after EXECUTE AS
SYSTEM_USER AS system_user,
USER_NAME() AS database_user; -- the database user it maps to (often dbo)
Use ORIGINAL_LOGIN() in code that may run under EXECUTE AS; SUSER_SNAME() then shows the impersonated login instead.
The detailed version: how did I authenticate?
SELECT s.login_name,
s.nt_domain,
s.nt_user_name, -- filled in only for Windows authentication
s.original_login_name,
s.host_name,
c.auth_scheme -- KERBEROS or NTLM = trusted; SQL = user id/password
FROM sys.dm_exec_sessions s
JOIN sys.dm_exec_connections c ON c.session_id = s.session_id
WHERE s.session_id = @@SPID;
| Connection type | login_name | nt_user_name | auth_scheme |
|---|---|---|---|
| Trusted (Windows) | DOMAIN\yourname | yourname | KERBEROS or NTLM |
| User ID / password | the SQL login | empty | SQL |
Seeing a user's own session needs no extra permission. To see other people's sessions in sys.dm_exec_sessions, you need VIEW SERVER STATE (in SQL Server 2022 and later, VIEW SERVER PERFORMANCE STATE is enough).
For Oracle DBAs
The closest Oracle equivalents are OS-authenticated users (IDENTIFIED EXTERNALLY, the old OPS$ accounts) and Kerberos authentication. To see who you are in Oracle:
SELECT SYS_CONTEXT('USERENV','SESSION_USER') AS db_user,
SYS_CONTEXT('USERENV','OS_USER') AS os_user,
SYS_CONTEXT('USERENV','AUTHENTICATION_METHOD') AS auth_method,
SYS_CONTEXT('USERENV','HOST') AS client_host
FROM dual;
More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

No comments:
Post a Comment