Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

asp.net

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
{
    get
    {
        WindowsIdentity identity = null;

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

        return identity.User;
    }
}
like image 649
Max Schmeling Avatar asked Jul 31 '09 18:07

Max Schmeling


People also ask

What is a user's SID?

The SID (Security IDentifier) is a unique ID number that a computer or domain controller uses to identify you. It is a string of alphanumeric characters assigned to each user on a Windows computer, or to each user, group, and computer on a domain-controlled network such as Indiana University's Active Directory.


1 Answers

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.

like image 65
Wyatt Barnett Avatar answered Sep 21 '22 19:09

Wyatt Barnett