Click here to Skip to main content
6,295,667 members and growing! (12,630 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Get The User Name In C# For NT Authentication

By Nick Parker

Through the .NET Framework you can easily get the current user name to authenticate.
C#.NET 1.0, Win2K, WinXP, Dev
Posted:19 May 2002
Updated:20 May 2002
Views:228,861
Bookmarked:60 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
29 votes for this article.
Popularity: 6.51 Rating: 4.45 out of 5
2 votes, 7.7%
1
1 vote, 3.8%
2

3
5 votes, 19.2%
4
18 votes, 69.2%
5

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


Member
Nick graduated from Iowa State University with a B.S. in Management Information System and a minor in Computer Science. Nick works for GeoLearning.

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 recently awarded the Visual C# MVP award from Microsoft.

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.
Occupation: Software Developer (Senior)
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 47 (Total in Forum: 47) (Refresh)FirstPrevNext
GeneralThanks Pinmemberirshadmohideen2:01 17 Jun '09  
GeneralGet the user name against a published application Pinmemberbtalaman10:48 22 Mar '09  
GeneralCan not get username in window server 2003 Pinmemberhkim_zoro16:04 6 Feb '09  
GeneralRe: Can not get username in window server 2003 PinprotectorNick Parker16:41 6 Feb '09  
GeneralRe: Can not get username in window server 2003 Pinmemberhkim_zoro16:54 6 Feb '09  
GeneralRe: Can not get username in window server 2003 PinmemberCraig C.9:39 6 Mar '09  
QuestionAPI Method Call Declare Function VBA to C# Question! Pinmemberandredani4:30 25 Aug '08  
GeneralVery useful PinmemberCliff Stanford4:38 5 Jun '08  
GeneralQurey Active directory with the login id to get the user Name Pinmemberrozhanin0:55 31 Mar '08  
Generallogged on user vs. currently executing user Pinmembernitstheone7:43 27 Mar '08  
GeneralRemote Username Pinmembercrouchie199813:52 12 May '07  
QuestionRetrieve login user's password PinmemberBiswajit Ghosh21:04 3 Apr '07  
AnswerRe: Retrieve login user's password PinprotectorNick Parker4:31 4 Apr '07  
GeneralRe: Retrieve login user's password PinmemberBiswajit Ghosh19:50 4 Apr '07  
GeneralRe: Retrieve login user's password Pinmemberkeych4:41 22 Aug '07  
GeneralHi there! Pinmemberkrishna nimmalapudi10:49 25 Apr '06  
GeneralRe: Hi there! PinprotectorNick Parker13:03 25 Apr '06  
GeneralReturns Machine Name PinmemberClank5:05 22 Jun '05  
GeneralRe: Returns Machine Name Pinmemberjklucker8:27 22 Jun '05  
GeneralRe: Returns Machine Name PinmemberClank8:57 22 Jun '05  
GeneralRe: Returns Machine Name Pinmemberltyao@yahoo.com12:49 12 Aug '05  
GeneralRe: Returns Machine Name PinmemberJonathan C Dickinson0:22 13 Aug '08  
GeneralNice... very nice!!! PinsussAnonymous10:03 16 May '05  
GeneralThanks!! Pinmembertagoh3:38 26 Apr '05  
GeneralHelp on Kernel.dll Pinmembersantosh poojari23:21 31 Mar '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 May 2002
Editor: Chris Maunder
Copyright 2002 by Nick Parker
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project