Search code examples
windowswinapivisual-c++windows-8microsoft-account

Get the local login name for the given Microsoft Account returned by NetWkstaUserEnum API on Windows 8 and above


I am using NetWkstaUserEnum() to get the local users name and its domain details.

Till Windows 7 it used to return only the login name and it worked fine. From Windows 8 onwards Microsoft Account was added and for this type of account the API started returning the Microsoft Account name instead of the local login name.

For example it returned [email protected] instead of usern_0000 which is the actual Windows local login name.

I cannot use NetUserEnum() as it does not return the domain name of the user.

So I need to get the local login name for the given Microsoft Account returned by NetWkstaUserEnum() API.

Any help will be appreciated.


Solution

  • Finally I was able to locate a way to get the Windows username for the given Microsoft Account.It uses NetUserGetInfo() to get the Microsoft Account name for the given username.

    Code Snippet:

    do
    {
        ntStatus    =   NetUserEnum(szSvr, 0, 0, (LPBYTE*)&userInfo0, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries, &dwResumeHandle);
        if( (ntStatus == NERR_Success) || (ntStatus == ERROR_MORE_DATA) )
        {
            tmpinfo = userInfo0;
            for( i = 0; (i < dwEntriesRead); i++ )
            {
                if(tmpinfo  != NULL)
                {
                    ntStatus    =   NetUserGetInfo(szSvr, tmpinfo->usri0_name, 24,(LPBYTE*)&userInfo24);
                    if(ntStatus == NERR_Success)
                    {
                        CString internetPrincipalName = (LPCWSTR) userInfo24->usri24_internet_principal_name;
                        if(LoginUsrStr.CompareNoCase(internetPrincipalName) == 0)
                        {
                            OutputDebugString("@@@@@@ Account Found @@@@@@");
                            localAccount = (LPCWSTR) tmpinfo->usri0_name;
                            userFound = TRUE;
                            break;
                        }
                    }
                }
                tmpinfo++;
            }
        }
    
        if( userInfo0 != NULL )
        {
            NetApiBufferFree( userInfo0 ) ;
            userInfo0 = NULL ;
        }
        if( userInfo24 != NULL )
        {
            NetApiBufferFree( userInfo24 ) ;
            userInfo24 = NULL ;
        }
    
    } while( userFound == FALSE && ntStatus == ERROR_MORE_DATA ) ;