다음을 통해 공유


BITS 전송 작업에 대한 서버 인증 자격 증명 지정

BITS(Background Intelligent Transfer Service) 전송 작업에 대해 다른 인증 체계를 지정할 수 있습니다.

다음 절차에서는 인증 체계를 가져오고 인증 ID 구조를 만듭니다. 그런 다음, 애플리케이션은 BITS 다운로드 작업을 만들고 작업에 대한 자격 증명을 설정합니다. 작업을 만든 후 애플리케이션은 콜백 인터페이스에 대한 포인터를 가져오고 BITS 전송 작업의 상태 폴링합니다. 작업이 완료되면 큐에서 제거됩니다.

이 예제에서는 예제: 공용 클래스에 정의된 헤더 및 구현을 사용합니다.

BITS 전송 작업에 대한 서버 인증 자격 증명을 지정하려면

  1. BG_AUTH_SCHEME 값을 체계 이름에 매핑하는 컨테이너 구조를 만듭니다.

    struct
    {
        LPCWSTR        Name;
        BG_AUTH_SCHEME Scheme;
    }
    SchemeNames[] =
    {
        { L"basic",      BG_AUTH_SCHEME_BASIC },
        { L"digest",     BG_AUTH_SCHEME_DIGEST },
        { L"ntlm",       BG_AUTH_SCHEME_NTLM },
        { L"negotiate",  BG_AUTH_SCHEME_NEGOTIATE },
        { L"passport",   BG_AUTH_SCHEME_PASSPORT },
    
        { NULL,         BG_AUTH_SCHEME_BASIC }
    };
    
  2. CCoInitializer 함수를 호출하여 COM 매개 변수를 초기화합니다. CCoInitializer 함수에 대한 자세한 내용은 예제: 공용 클래스를 참조하세요.

  3. BG_AUTH_CREDENTIALS 구조를 준비합니다. 이 예제에서는 SecureZeroMemory 함수를 사용하여 중요한 정보와 연결된 메모리 위치를 지웁 수 있습니다. SecureZeroMemory 함수는 WinBase.h에 정의되어 있습니다.

  4. GetScheme 함수를 사용하여 서버에 연결하는 데 사용할 인증 체계를 가져옵니다.

    bool GetScheme( LPCWSTR s, BG_AUTH_SCHEME *scheme )
    {
        int i;
    
        i = 0;
        while (SchemeNames[i].Name != NULL)
        {
            if (0 == _wcsicmp( s, SchemeNames[i].Name ))
            {
    
                *scheme = SchemeNames[i].Scheme;
                return true;
            }
    
            ++i;
        }
    
        return false;
    }
    
  5. BG_AUTH_CREDENTIALS 구조를 GetScheme 함수에서 반환한 인증 체계와 ServerAuthentication 함수에 전달된 사용자 이름 및 암호로 채웁니다.

  6. IBackgroundCopyJob 인터페이스(pJob)에 대한 포인터를 가져옵니다.

  7. CoInitializeSecurity를 호출하여 COM 프로세스 보안을 초기화합니다. BITS에는 적어도 IMPERSONATE 수준의 가장이 필요합니다. 올바른 가장 수준이 설정되지 않은 경우 E_ACCESSDENIED BITS가 실패합니다.

  8. IBackgroundCopyManager 인터페이스에 대한 포인터를 가져오고 CoCreateInstance 함수를 호출하여 BITS에 대한 초기 로케이터를 가져옵니다.

  9. IBackgroundCopyManager::CreateJob 메서드를 호출하여 BITS 전송 작업을 만듭니다.

  10. CNotifyInterface 콜백 인터페이스에 대한 포인터를 가져와 서 IBackgroundCopyJob::SetNotifyInterface 메서드를 호출하여 작업 관련 이벤트에 대한 알림을 받습니다. CNotifyInterface에 대한 자세한 내용은 예제: 공용 클래스를 참조하세요.

  11. IBackgroundCopyJob::SetNotifyFlags 메서드를 호출하여 받을 알림 유형을 설정합니다. 이 예제에서는 BG_NOTIFY_JOB_TRANSFERREDBG_NOTIFY_JOB_ERROR 플래그가 설정됩니다.

  12. IBackgroundCopyJob2 인터페이스에 대한 포인터를 가져옵니다. IBackgroundCopyJob2 포인터를 사용하여 작업에 대한 추가 속성을 설정합니다. 이 프로그램은 IBackgroundCopyJob2::SetCredentials 메서드를 사용하여 BITS 전송 작업에 대한 자격 증명을 설정합니다.

  13. IBackgroundCopyJob::AddFile을 호출하여 BITS 전송 작업에 파일을 추가합니다. 이 예제에서 IBackgroundCopyJob::AddFile 메서드는 ServerAuthentication 함수에 전달된 remoteFile 및 localFile 변수를 사용합니다.

  14. 파일이 추가된 후 IBackgroundCopyJob::Resume 을 호출하여 작업을 다시 시작합니다.

  15. 작업이 전송되는 동안 콜백 인터페이스에서 메시지 종료를 기다리도록 while 루프를 설정합니다.

    참고

    이 단계는 COM 아파트가 단일 스레드 아파트인 경우에만 필요합니다. 자세한 내용은 단일 스레드 아파트를 참조하세요.

     

    // Wait for QuitMessage from CallBack
        DWORD dwLimit = GetTickCount() + (15 * 60 * 1000);  // set 15 minute limit
        while (dwLimit > GetTickCount())
        {
            MSG msg;
    
            while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 
            { 
                // If it is a quit message, exit.
                if (msg.message == WM_QUIT) 
                {
                    return;
                }
    
                // Otherwise, dispatch the message.
                DispatchMessage(&msg); 
            } // End of PeekMessage while loop
        }
    

    위의 루프는 GetTickCount 함수를 사용하여 작업이 전송되기 시작한 후 경과된 시간(밀리초)을 검색합니다.

  16. BITS 전송 작업이 완료되면 IBackgroundCopyJob::Complete를 호출하여 큐에서 작업을 제거합니다.

다음 코드 예제에서는 BITS 전송 작업에 대한 서버 인증 자격 증명을 지정합니다.

#include <bits.h>
#include <bits4_0.h>
#include <stdio.h>
#include <tchar.h>
#include <lm.h>
#include <iostream>
#include <exception>
#include <string>
#include <atlbase.h>
#include <memory>
#include <new>
#include "CommonCode.h"

//
// Retrieve BG_AUTH_SCHEME from scheme name.
//
//
struct
{
    LPCWSTR        Name;
    BG_AUTH_SCHEME Scheme;
}
SchemeNames[] =
{
    { L"basic",      BG_AUTH_SCHEME_BASIC },
    { L"digest",     BG_AUTH_SCHEME_DIGEST },
    { L"ntlm",       BG_AUTH_SCHEME_NTLM },
    { L"negotiate",  BG_AUTH_SCHEME_NEGOTIATE },
    { L"passport",   BG_AUTH_SCHEME_PASSPORT },

    { NULL,         BG_AUTH_SCHEME_BASIC }
};

bool GetScheme( LPCWSTR s, BG_AUTH_SCHEME *scheme )
{
    int i;

    i = 0;
    while (SchemeNames[i].Name != NULL)
    {
        if (0 == _wcsicmp( s, SchemeNames[i].Name ))
        {

            *scheme = SchemeNames[i].Scheme;
            return true;
        }

        ++i;
    }

    return false;
}

void ServerAuthentication(const LPWSTR &remoteFile, const LPWSTR &localFile, const LPWSTR &scheme, const LPWSTR &username, const LPWSTR &password)
{

 // If CoInitializeEx fails, the exception is unhandled and the program terminates  
 CCoInitializer coInitializer(COINIT_APARTMENTTHREADED);
    
    // Prepare the credentials structure.
    BG_AUTH_CREDENTIALS cred;
    ZeroMemory(&cred, sizeof(cred));
    if (!GetScheme(scheme,&cred.Scheme))
    {
        wprintf(L"Invalid authentication scheme specified\n");
        return;
    }

    cred.Target = BG_AUTH_TARGET_SERVER;
    cred.Credentials.Basic.UserName = username;
    if (0 == _wcsicmp(cred.Credentials.Basic.UserName, L"NULL"))
    {
        cred.Credentials.Basic.UserName = NULL;
    }

    cred.Credentials.Basic.Password = password;
    if (0 == _wcsicmp(cred.Credentials.Basic.Password, L"NULL"))
    {
        cred.Credentials.Basic.Password = NULL;
    }

    CComPtr<IBackgroundCopyJob> pJob;
    try
    {
        //The impersonation level must be at least RPC_C_IMP_LEVEL_IMPERSONATE.
        HRESULT hr = CoInitializeSecurity(NULL, 
            -1, 
            NULL, 
            NULL,
            RPC_C_AUTHN_LEVEL_CONNECT,
            RPC_C_IMP_LEVEL_IMPERSONATE,
            NULL, 
            EOAC_DYNAMIC_CLOAKING, 
            0);
        if (FAILED(hr))
        {
            throw MyException(hr, L"CoInitializeSecurity");
        }

        // Connect to BITS.
        CComPtr<IBackgroundCopyManager> pQueueMgr;
        hr = CoCreateInstance(__uuidof(BackgroundCopyManager), NULL,
            CLSCTX_LOCAL_SERVER,
            __uuidof(IBackgroundCopyManager),
            (void**)&pQueueMgr);

        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"CoCreateInstance");
        }

        // Create a job.
        wprintf(L"Creating Job...\n");

        GUID guidJob;
        hr = pQueueMgr->CreateJob(L"BitsAuthSample",
            BG_JOB_TYPE_DOWNLOAD,
            &guidJob,
            &pJob);

        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"CreateJob");
        }

        // Set the File Completed call.
        CComPtr<CNotifyInterface> pNotify;
        pNotify = new CNotifyInterface();
        hr = pJob->SetNotifyInterface(pNotify);
        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"SetNotifyInterface");
        }
        hr = pJob->SetNotifyFlags(BG_NOTIFY_JOB_TRANSFERRED | 
            BG_NOTIFY_JOB_ERROR);

        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"SetNotifyFlags");
        }

        // Set credentials.
        CComPtr<IBackgroundCopyJob2> job2;
        hr = pJob.QueryInterface(&job2);
        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"QueryInterface");
        }

        hr = job2->SetCredentials(&cred);
        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"SetCredentials");
        }

        // Add a file.
        wprintf(L"Adding File to Job\n");
        hr = pJob->AddFile(remoteFile, localFile);
        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"AddFile");
        }

        //Resume the job.
        wprintf(L"Resuming Job...\n");
        hr = pJob->Resume();
        if (FAILED(hr))
        {
            // Failed to connect.
            throw MyException(hr, L"Resume");
        }
    }
    catch(const std::bad_alloc &)
    {
        wprintf(L"Memory allocation failed");
        if (pJob)
        {
            pJob->Cancel();
        }

        return;
    }
    catch(const MyException &ex)
    {
        wprintf(L"Error %x occurred during operation", ex.Error);
        if (pJob)
        {
            pJob->Cancel();
        }

        return;
    }

    wprintf(L"Transferring file and waiting for callback.\n");

    // Wait for QuitMessage from CallBack.
    DWORD dwLimit = GetTickCount() + (15 * 60 * 1000);  // set 15 minute limit
    while (dwLimit > GetTickCount())
    {
        MSG msg;

        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 
        { 
            // If it is a quit message, exit.
            if (msg.message == WM_QUIT) 
            {
                return;
            }

            // Otherwise, dispatch the message.
            DispatchMessage(&msg); 
        } // End of PeekMessage while loop
    }

    pJob->Cancel();
    return;
}

void _cdecl _tmain(int argc, LPWSTR* argv)
{   
    if (argc != 6)
    {
        wprintf(L"Usage:");
        wprintf(L"%s", argv[0]);
        wprintf(L" [remote name] [local name] [server authentication scheme =\"NTLM\"|\"NEGOTIATE\"|\"BASIC\"|\"DIGEST\"] [username] [password]\n");
        return;
    }

    ServerAuthentication(argv[1], argv[2], argv[3], argv[4], argv[5]); 

}

IBackgroundCopyManager

IBackgroundCopyJob

IBackgroundCopyJob2

예: 공통 클래스