[SOLVED] What is the best way to get the current user's SID?


Prerequisite Detail

  1. Working in .NET 2.0.
  2. The code is in a common library that could be called from ASP.Net, Windows Forms, or a Console application.
  3. Running in a Windows Domain on a corporate network.

The Question

What is the best way to get the current user’s SID? I’m not talking about the identity that is executing the application, but the user who is accessing the interface. In background applications and desktop based applications this should be the identity actually executing the application, but in ASP.Net (without impersionation) this should be the HttpContext.Current.User SID.

The Current Method

This is what I’ve got right now. It just seems… wrong. It’s nasty. Is there a better way to do this, or some built in class that does it for you?

public static SecurityIdentifier SID
        WindowsIdentity identity = null;

        if (HttpContext.Current == null)
            identity = WindowsIdentity.GetCurrent();
            identity = HttpContext.Current.User.Identity as WindowsIdentity;

        return identity.User;


I don’t think there is a better way at getting at this info–you’ve got to get at the WindowsPrincipal somehow and .NET’s rather clean API abstracts that behind the User object. I’d just leave this nice and wrapped up in a method and call it a day.

Well, ok, there is one thing you should do (unless your web users are always going to be WindowsIdentity), which would be to check for null identity and handle it according to whatever rules you have.

Answered By – Wyatt Barnett

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *