Archive for category IIS (Internet Information Services)

How to get the currently logged on user id in .Net / Web app

There are a few steps to getting the currently logged on user in a web app. First there is the code, which is quite simple. This is it:

VB.Net
Dim userName As String = My.User.Name
C#.Net
String userName = this.User.Identity.Name

There is some detail on this page as to how to parse out just the name from the domain:
http://vbdotnetforum.com/index.php?/topic/411-get-username-of-logged-on-user/, though you really shouldn’t do this. In a properly constructed organization if there are multiple domains, say domain1 and domain2 then these users:
domain1\aUser
domain2\aUser
are not the same person. So using just the name without the domain is invalid logic.

Now that you have the code to get the current user you may find that it always returns an empty string, “”. If this is occurring it means that your website is not properly passing integrated windows authentication information to your app. This won’t happen in a fat client application but is likely to happen in a web app.

To enable authentication in your development environment change the authentication mode to “Windows” in your web.config like so:

<authentication mode=”Windows”>
</authentication>

This node is a child of <system.web> in vs2010.

Deploying this app to IIS should result in Windows authentication, as per the app.config file, if not the steps to configure a Virtual Directory are:
Open IIS admin-> Find your Virtual Directory->r-click on it->Properties->Directory Security->Under the heading “Anonymous access and authentication control” click Edit->Uncheck “Anonymous access”, check “Integrated Windows authentication”.

That’s it, happy integrated auth!

EDIT:
It turns out there are a number of headaches involved in getting integrated auth to work when calling from a windows form app to a webservice.  For the life of me I couldn’t get a VS2010 app to call a website hosted on an older version of IIS.  I imagine this is an issue with IIS being out of date, but seriously.  Integrated Auth has been around for ages, there HAS to be a way.

Anyway, I digress.  It turns out not everything implements IPrincipal so you can’t always use this.User to get the user.  If that doesn’t work there are these options as well:
Environment.UserName
or
System.Windows.Forms.SystemInformation.UserName

If you know how to get VS2010 to call a webservice hosted on IIS 4 using integrated authentication be sure to let me know.

Leave a comment