Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can WindowsIdentity.GetCurrent() return null?

ReSharper warns me about a possible NullReferenceException in

WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);

I looked in MSDN doc but didn't see any mention of this. Also, it doesn't make sense since if you run an executable, you have to be logged on.

Is this just a ReSharper search pattern?

like image 662
Noich Avatar asked Apr 14 '13 11:04

Noich


1 Answers

Using ILSpy, you can look at a decompiled version of GetCurrent and GetCurrentInternal, which GetCurrent calls.

GetCurrent:

public static WindowsIdentity GetCurrent()
{
    return WindowsIdentity.GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false);
}

GetCurrentInternal:

internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly)
{
    int errorCode = 0;
    bool flag;
    SafeTokenHandle currentToken = WindowsIdentity.GetCurrentToken(desiredAccess, threadOnly, out flag, out errorCode);
    if (currentToken != null && !currentToken.IsInvalid)
    {
        WindowsIdentity windowsIdentity = new WindowsIdentity();
        windowsIdentity.m_safeTokenHandle.Dispose();
        windowsIdentity.m_safeTokenHandle = currentToken;
        return windowsIdentity;
    }
    if (threadOnly && !flag)
    {
        return null;
    }
    throw new SecurityException(Win32Native.GetMessage(errorCode));
}

Since threadOnly is always false when calling from GetCurrent, and the currentToken must be valid for the other return statement, I don't think you're at risk of getting a null WindowsIdentity.

like image 135
nitzanms Avatar answered Oct 12 '22 23:10

nitzanms