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:

Dim userName As String = My.User.Name
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:, though you really shouldn’t do this. In a properly constructed organization if there are multiple domains, say domain1 and domain2 then these users:
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”>

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!

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:

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

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: