Can WindowsIdentity.GetCurrent() return null?

后端 未结 1 850
我在风中等你
我在风中等你 2021-02-19 17:19

ReSharper warns me about a possible NullReferenceException in

WindowsIdentity windowsIdentity = new WindowsIde         


        
1条回答
  •  囚心锁ツ
    2021-02-19 18:15

    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.

    0 讨论(0)
提交回复
热议问题