Can WindowsIdentity.GetCurrent() return null?

后端 未结 1 1805
失恋的感觉
失恋的感觉 2021-02-19 17:13

ReSharper warns me about a possible NullReferenceException in

WindowsIdentity windowsIdentity = new WindowsIde         


        
相关标签:
1条回答
  • 2021-02-19 17:58

    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)
提交回复
热议问题