Click here to Skip to main content
Click here to Skip to main content

Get The User Name In C# For NT Authentication

By , 20 May 2002
 

Introduction

Our department has recently begun moving all of our Client/Server Applications over to Windows NT authentication via Active Directory. Our previous applications used a SQL Server login for each user. This can become very tedious when it come to setting up users across the company for wide spread applications. There are also inherent security risks involved without the user being authenticated. I thought I would share the following code dealing with security in .NET in hopes that it will help someone else.

Our applications are done in Visual Basic, so we of course have to make a Windows API call where we have defined the following function:

Old VB6 Windows API Method Call

Declare Function GetUserName Lib "advapi32.dll" Alias _
                "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

This is not difficult at all, however I have been playing around with C# lately and I thought it would be interesting to find out how we will do this in managed code.

My first idea was to do an import of the above mentioned advapi32.dll along with the method we will use to get the user name. There have been many other examples on Code Project where users have imported methods through existing .dll's, so hopefully some of this looks familiar. I have tried to document what is going on here, even though it is rather simple. The following code will require you to add using statement as well.

Possible New C# Managed Method

//====================================================
//Include at the top, above the namespace declaration.

using System.Runtime.InteropServices;


//=====================================================
//Defines the .dll file to import as well as the method 
//to use.

[DllImport("Advapi32.dll", EntryPoint="GetUserName", 
		ExactSpelling=false, SetLastError=true)]


//====================================================
//This specifies the exact method we are going to call 
//from within our imported .dll

static extern bool GetUserName(
	[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
	[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize );


//===================================================
//The following is the implementation of our imported 
//method.

	byte[] str=new byte[256];
	Int32[] len=new Int32[1];
	len[0]=256;
	GetUserName(str,len);      
	MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));

What I thought was an instant solution actually made me think a little harder about my initial problem. There must be a better way to get the username than by making an old Windows API call. Upon doing a little research I have come to the conclusion that the boys over at Microsoft did manage to include this into the .NET Framework rather seamlessly. I was rather shocked when I found out how very simple it was. You will only need the following:

Most Sensible C# Method

//=======================================================
//Place this at the top, above your namespace declaration

using System.Security.Principal;


//=======================================================
//In a specific event, place the following.

string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

MessageBox.Show(a.ToString());

The System.Security.Principal.WindowsIdentity.GetCurrent() section opens us up to more than just the current user. When looking you will find the following additional methods/properties within this section of the .NET Framework:
  • AuthenticationType - Get's the type of authentication used to authenticate the user.
  • Impersonates - Impersonates the user represented by the object.
  • IsAnonymous - Indicates whether the user account is identified as an anonymous account by the system.
  • IsAuthenticated - Determines if the user has been authenticated by Windows.
  • IsGuest - Indicates whether the account is defined as a guest account by the system.
  • IsSystem - Indicates whether the account is defined as a system account by the system.
That’s it! There isn’t a whole lot to it and we don’t even have to do any of the ugly importation of old .dll’s. Hope this helps someone, I found it to be rather interesting.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nick Parker
Software Developer (Senior)
United States United States
Member
Nick graduated from Iowa State University with a B.S. in Management Information System and a minor in Computer Science. Nick works for Zetetic.
 
Nick has also been involved with the Iowa .NET User Group since it's inception, in particular giving presentations over various .NET topics. Nick was awarded the Visual C# MVP award from Microsoft for four years in a row.
 
In his mystical spare time he is working on a development project called "DeveloperNotes" which integrates into Visual Studio .NET allowing developers easy access to common code pieces. He is also a fan of using dynamically typed languages to perform unit testing, not to mention how he loves to talk about himself in the third person.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberaankss221 Feb '12 - 23:27 
GeneralThanx!memberWarmBlanke11 Nov '09 - 2:44 
QuestionHow to create database that contains usersmembersanshine198723 Jul '09 - 4:16 
GeneralThanksmemberirshadmohideen17 Jun '09 - 1:01 
GeneralGet the user name against a published applicationmemberbtalaman22 Mar '09 - 9:48 
QuestionCan not get username in window server 2003memberhkim_zoro6 Feb '09 - 15:04 
AnswerRe: Can not get username in window server 2003protectorNick Parker6 Feb '09 - 15:41 
GeneralRe: Can not get username in window server 2003memberhkim_zoro6 Feb '09 - 15:54 
GeneralRe: Can not get username in window server 2003memberCraig C.6 Mar '09 - 8:39 
GeneralRe: Can not get username in window server 2003 [modified]memberantonu21 Dec '09 - 23:04 
QuestionAPI Method Call Declare Function VBA to C# Question!memberandredani25 Aug '08 - 3:30 
GeneralVery usefulmemberCliff Stanford5 Jun '08 - 3:38 
GeneralQurey Active directory with the login id to get the user Namememberrozhanin30 Mar '08 - 23:55 
Generallogged on user vs. currently executing usermembernitstheone27 Mar '08 - 6:43 
GeneralRemote Usernamemembercrouchie199812 May '07 - 12:52 
QuestionRetrieve login user's passwordmemberBiswajit Ghosh3 Apr '07 - 20:04 
AnswerRe: Retrieve login user's passwordprotectorNick Parker4 Apr '07 - 3:31 
GeneralRe: Retrieve login user's passwordmemberBiswajit Ghosh4 Apr '07 - 18:50 
GeneralRe: Retrieve login user's passwordmemberkeych22 Aug '07 - 3:41 
GeneralHi there!memberkrishna nimmalapudi25 Apr '06 - 9:49 
GeneralRe: Hi there!protectorNick Parker25 Apr '06 - 12:03 
GeneralReturns Machine NamememberClank22 Jun '05 - 4:05 
GeneralRe: Returns Machine Namememberjklucker22 Jun '05 - 7:27 
GeneralRe: Returns Machine NamememberClank22 Jun '05 - 7:57 
GeneralRe: Returns Machine Namememberltyao@yahoo.com12 Aug '05 - 11:49 
GeneralRe: Returns Machine NamememberJonathan C Dickinson12 Aug '08 - 23:22 
GeneralNice... very nice!!!sussAnonymous16 May '05 - 9:03 
GeneralThanks!!membertagoh26 Apr '05 - 2:38 
GeneralHelp on Kernel.dllmembersantosh poojari31 Mar '05 - 22:21 
GeneralRe: Help on Kernel.dllprotectorNick Parker1 Apr '05 - 1:18 
GeneralDidn't Work in Web Formmemberjenken398nj27 Jul '04 - 11:44 
GeneralRe: Didn't Work in Web FormprotectorNick Parker27 Jul '04 - 17:53 
QuestionHow do I get the Username in Windows Services?memberbpmtri17 Jul '04 - 19:45 
AnswerRe: How do I get the Username in Windows Services?memberHari Kishan Charora17 May '06 - 12:18 
JokeRe: How do I get the Username in Windows Services?membercarstenborg19 Jun '06 - 20:25 
GeneralRe: How do I get the Username in Windows Services?membermycsharpcorner28 Nov '08 - 18:58 
GeneralTo simplify...sussPaul Wojcicki Jarocki24 Jun '04 - 13:00 
GeneralUser ID on Pocket PCmemberIridium19 Mar '04 - 13:35 
GeneralUnable to download codememberTerry Ward22 Sep '03 - 4:51 
GeneralRe: Unable to download codeeditorNick Parker22 Sep '03 - 6:12 
GeneralRe: Unable to download codememberTerry Ward22 Sep '03 - 6:23 
GeneralWindowsIdentity.GetCurrent()sussA. A.19 Apr '03 - 4:34 
GeneralNT authenticationmemberMuthukumar2 Jan '03 - 8:42 
GeneralRe: NT authenticationeditorNick Parker3 Jan '03 - 8:02 
QuestionWhat's wrong with this?memberJohn Burton20 May '02 - 22:42 
AnswerRe: What's wrong with this?memberNick Parker21 May '02 - 1:06 
AnswerRe: What's wrong with this?memberBlake Coverett21 May '02 - 3:04 
GeneralRe: What's wrong with this?memberJohn Burton21 May '02 - 22:16 
GeneralRe: What's wrong with this?memberNick Parker22 May '02 - 8:08 
GeneralRe: What's wrong with this?memberJohn Burton22 May '02 - 11:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 21 May 2002
Article Copyright 2002 by Nick Parker
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid