Microsoft MVP성태의 닷넷 이야기
VC++: 84. CredUIPromptForWindowsCredentials Win32 API 사용법 정리 [링크 복사], [링크+제목 복사],
조회: 24120
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 5개 있습니다.)
VC++: 84. CredUIPromptForWindowsCredentials Win32 API 사용법 정리
; https://www.sysnet.pe.kr/2/0/1827

VC++: 85. Windows Vista부터 바뀐 Credential Provider 예제 분석 (1)
; https://www.sysnet.pe.kr/2/0/1828

VC++: 86. Windows Vista부터 바뀐 Credential Provider 예제 분석 (2)
; https://www.sysnet.pe.kr/2/0/1829

.NET Framework: 927. C# - 윈도우 프로그램에서 Credential Manager를 이용한 보안 정보 저장
; https://www.sysnet.pe.kr/2/0/12267

닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기
; https://www.sysnet.pe.kr/2/0/13744




CredUIPromptForWindowsCredentials Win32 API 사용법 정리

인증 정보를 받기 위한 대화창으로 (비스타 이상에서만 제공되는) CredUIPromptForWindowsCredentials Win32 API를 사용할 수 있습니다.

CredUIPromptForWindowsCredentials function
; https://learn.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-creduipromptforwindowscredentialsa

간단한 대화창이지만, 이것을 사용해서 좋은 이유는 운영체제에 등록된 각종 Credential Provider를 감안한 인증창을 띄워주기 때문에 윈도우 통합 인증을 구현하는 시나리오에서 충분한 장점이 있습니다. 비스타/2008 운영체제부터 기존의 MS GINA(Graphical Identification and Authentication)를 대체한 새로운 Credential Provider 인증 모델을 제공하는데요.

Windows Vista용 자격 증명 공급자로 사용자 지정 로그인 환경 만들기
; https://learn.microsoft.com/ko-kr/archive/msdn-magazine/2007/january/custom-login-experiences-credential-providers-in-windows-vista

CredUIPromptForWindowsCredentials API가 Credential Provider를 활성화하기 때문에 사용자 정의 Credential Provider 인증 모듈을 개발할 때 디버깅을 쉽게 할 수 있는 용도로도 사용됩니다.

API 사용 코드는 꽤나 전형적입니다.

BOOL save = false;
DWORD authPackage = 0;
LPVOID authBuffer;
ULONG authBufferSize = 0;
CREDUI_INFO credUiInfo;
DWORD dwFlags = 0;

credUiInfo.pszCaptionText = L"My caption";
credUiInfo.pszMessageText = L"My message";
credUiInfo.cbSize = sizeof(credUiInfo);
credUiInfo.hbmBanner = NULL;
credUiInfo.hwndParent = NULL;

DWORD dwResult = CredUIPromptForWindowsCredentials(&(credUiInfo), 0, &(authPackage),
    NULL, 0, &authBuffer, &authBufferSize, &(save), dwFlags);

if (dwResult == ERROR_SUCCESS)
{
    ::OutputDebugString(L"ERROR_SUCCESS");

    // 사용 후, 보안을 위해 인증 정보를 담은 영역을 '\0'로 지워준다.
    SecureZeroMemory(authBuffer, authBufferSize);
    CoTaskMemFree(authBuffer);
}
else if (dwResult == ERROR_CANCELLED)
{
    ::OutputDebugString(L"ERROR_CANCELLED");
}
else
{
    ::OutputDebugString(L"ERROR");
}

위의 코드를 실행하면 다음과 같은 대화창이 뜹니다.

cred_dlg_1.png

아무 텍스트나 입력 후 "OK" 버튼을 누르면 ERROR_SUCCESS, "Cancel" 버튼을 누르면 ERROR_CANCELLED가 반환됩니다. (구체적으로 ERROR를 반환하는 시나리오는 잘 모르겠습니다.)

'아무 텍스트'나 입력하는 것이기 때문에, CredUIPromptForWindowsCredentials 함수는 사용자가 입력한 정보가 실제 인증된 계정인지에 대한 여부까지는 확인하지 않습니다. 말 그대로 사용자가 입력한 계정 정보만을 인자로 넘겨줬던 authBuffer 포인터와 authBufferSize로 알려줍니다. 실제로 반환 시점에 디버깅을 통해 authBuffer 포인터를 확인하면 이렇습니다.

cred_dlg_2.png

위의 화면에서는 사용자가 계정 정보에 "test", 암호에 "qwer"을 입력했을 때의 반환값을 보여주고 있습니다. 바이너리 구조체이고, 그 내부에 사용자가 입력한 계정(THEMYTH8\test)과 암호(위의 그림에서 test 문자열 이후로 있는 정보)가 들어있습니다. 다행히, 이 정보를 해석하는 CredUnPackAuthenticationBuffer API가 있습니다. 따라서 dwResult == ERROR_SUCCESS인 경우 아래의 코드와 같은 식으로 사용자가 입력한 계정 정보를 구할 수 있습니다.

wchar_t userBuffer[1024];
wchar_t domainBuffer[1024];
wchar_t passwordBuffer[1024];

ULONG userBufferSize = 1024;
ULONG domainBufferSize = 1024;
ULONG passwordBufferSize = 1024;

BOOL success = CredUnPackAuthenticationBuffer(CRED_PACK_PROTECTED_CREDENTIALS,
    authBuffer, authBufferSize,
    userBuffer, &userBufferSize,
    domainBuffer, &domainBufferSize,
    passwordBuffer, &passwordBufferSize);
if (success == TRUE)
{
    // userBuffer == THEMYTH8\\test (여기서, THEMYTH8은 컴퓨터 명)
    // domainBuffer == (변화없음, Active Directory에 참여한 PC에만 유효한 값을 반환)
    // passwordBuffer == qwer
}

따라서, 사용자가 입력한 정보 중 암호는 '암호화된 상태'로 전달받고 필요한 경우 CredUnPackAuthenticationBuffer를 평문으로 복원해 사용할 수 있습니다.

참고로, C#(.NET)에서 사용하고 싶다면 다음의 유틸리티 클래스들을 이용하시면 좋습니다. ^^

Windows Common Credential UI Helper for .NET Framework
; https://gist.github.com/mayuki/339952

CredUIPromptForWindowsCredentials return junk characters if you P/Invoke it from managed code on OS’s such as Spanish or French.
; (broken) http://blogs.msdn.com/b/dsnotes/archive/2012/02/21/creduipromptforwindowscredentials-return-junk-characters-if-you-p-invoke-it-from-managed-code-on-os-s-such-as-spanish-or-french.aspx




CredUIPromptForWindowsCredentials API에 전달하는 옵션 중 마지막 인자인 "DWORD dwFlags"에 대해 알아보겠습니다.


1. dwFlags == CREDUIWIN_CHECKBOX

이 값으로 CREDUIWIN_CHECKBOX가 전달되면,

BOOL save = FALSE;
DWORD authPackage = 0;
LPVOID authBuffer;
ULONG authBufferSize = 0;
CREDUI_INFO credUiInfo;

// ...

DWORD dwFlags = CREDUIWIN_CHECKBOX;

DWORD dwResult = CredUIPromptForWindowsCredentials(&(credUiInfo), 0, &(authPackage),
    NULL, 0, &authBuffer, &authBufferSize, &(save), dwFlags);

이렇게 "Remember my credentials" 선택 상자가 보여집니다.

cred_dlg_3.png

사용자가 이 값을 설정했는지의 여부는 8번째 인자인 "_Inout_opt_ BOOL *pfSave"로 알아낼 수 있습니다. 물론, 전달 시 "TRUE"로 해주면 대화창에서는 미리 선택된 체로 나옵니다.


2. dwFlags == CREDUIWIN_GENERIC

CREDUIWIN_GENERIC인 경우, CredUIPromptForWindowsCredentials API는 시스템에 등록된 사용자 정의 Credential Provider는 활성화시키지 않습니다. 또한 호출 후의 authBuffer에는 사용자가 입력한 '암호' 문자열이 평문으로 포함됩니다.


3. dwFlags == CREDUIWIN_IN_CRED_ONLY

시스템에 등록된 사용자 정의 Credential Provider 중, 원하는 Provider를 지정해서 활성화시킬 수 있습니다.


4. dwFlags == CREDUIWIN_ENUMERATE_ADMINS

활성화된 Credential Provider들은, 이 옵션이 전달된 경우 관리자 계정들만 열람해서 값을 반환해야 합니다. 문서에 따르면 "This value is intended for User Account Control (UAC) purposes only. We recommend that external callers not set this flag."라고 하면서 일반 사용자 응용 프로그램에서 쓰는 것을 권장하지 않고 있습니다.


5. dwFlags == CREDUIWIN_SECURE_PROMPT

긴말 필요없이, 이 옵션은 현실적으로 전달하고 싶지 않을 것입니다. (전달 시, 사용자 입장에서 너무 불편합니다.)

대충 이 정도 옵션만 다루고, 행여 나중에 또 필요한 경우가 생기면 다른 옵션도 설명할 기회를 갖겠습니다. ^^





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 9/28/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11099정성태11/7/201630740.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드파일 다운로드1
11098정성태11/7/201620089오류 유형: 368. 빌드 이벤트에서 robocopy 사용 시 $(TargetDir) 매크로를 지정하는 경우 오류 발생
11097정성태11/7/201623015오류 유형: 367. go install: no install location for directory [...경로...] outside GOPATH
11096정성태11/6/201626820디버깅 기술: 83. PDB 파일을 수동으로 다운로드하는 방법
11095정성태11/6/201623086.NET Framework: 619. C# - Cognitive Services 중의 하나인 Face API를 사용해 얼굴 인식 및 흐림(blur) 효과 적용 [1]파일 다운로드1
11094정성태11/5/201624708VC++: 105. Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력
11093정성태11/4/201624638웹: 34. Edge 브라우저도 지원하는 클립보드 복사를 위한 자바스크립트 코드
11092정성태11/3/201631593.NET Framework: 618. C# - NAudio를 이용한 MP3 파일 재생 [5]파일 다운로드1
11091정성태11/3/201626318VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201627780VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201626700디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201630771.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201625194.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201619037오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201633440.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201621408오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201627946Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201629877.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
11081정성태10/26/201620378오류 유형: 364. You need to fix your Microsoft Account for apps on your other devices to be able to launch apps and continue experiences on this device.
11080정성태10/24/201623541Windows: 130. Windows Server 2016 Nano 서버 설치 방법
11079정성태10/21/201620670Windows: 129. Windows Server 2016 설치 CD에 있는 Convert-WindowsImage.ps1 사용 방법 정리
11078정성태10/21/201621971Windows: 128. Windows Server 2016 Nano 서버 VHD 이미지 만드는 방법 - TP5 기준
11077정성태10/21/201620468오류 유형: 363. Active Directory 서버의 NETLOGON 서비스가 멈췄을 때 발생하는 문제
11076정성태10/21/201620078오류 유형: 362. 윈도우 백업 시 오류 - 0x80780040
11075정성태10/20/201621001Windows: 127. Convert-WindowsImage.ps1 사용 방법 정리
11074정성태10/20/201629304Windows: 126. Windows Server 2016 평가판을 정식 버전으로 라이선스 변경하는 방법
... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...