Friday, 3 March 2017

resharper - 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?


Answer



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

The result is:



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...