Microsoft MVP성태의 닷넷 이야기
.NET Framework: 227. basicHttpBinding + 사용자 정의 인증 구현 [링크 복사], [링크+제목 복사],
조회: 19882
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

basicHttpBinding + 사용자 정의 인증 구현


예전에도 WCF의 사용자 정의 인증 구현 예제를 소개해 드렸는데요.

WCF 사용자 정의 인증 구현 예제
; https://www.sysnet.pe.kr/2/0/864

위의 예제는 다음과 같은 특징들이 있습니다.

  • netTcpBinding
  • 독립실행형 EXE에서 WCF 서버 호스팅
  • <security mode="Message" /> 사용
  • 사용자 정의 인증 사용

하지만, 이번에는 다음과 같은 특징을 가진 WCF 예제를 소개해드릴려고 합니다.

  • basicHttpBinding
  • IIS / HTTPS 사용
  • <security mode="TransportWithMessageCredential" /> 사용
  • 사용자 정의 인증 사용




단적으로 말해서, 이번 글은 제가 기존에 써 두었던 "WCF 사용자 정의 인증 구현 예제"에서 다음의 글에 나오는 요소를 더하면 됩니다.

Username Authentication over basicHttpBinding with WCF’s ChannelFactory Interface
; http://nirajrules.wordpress.com/2009/05/22/username-over-https-custombinding-with-wcf%E2%80%99s-channelfactory-interface/

처음부터 예제를 만들기보다는, 지난번 글에 실린 예제 코드에서 살을 붙이는 식으로 진행해 볼 텐데 이를 위해 우선 다음의 예제 코드를 다운로드합니다.

WcfUserName.zip
; https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=529&boardid=331301885

솔루션 파일을 Visual Studio IDE에서 로드한 후 웹 애플리케이션을 하나 생성하고 기존의 UserNamePasswordAuth 프로젝트를 참조 추가 및 예제용으로 TestService.svc 서비스를 하나 생성합니다.

다음으로 TestService.svc에 대한 사용자 정의 인증 구현 설정을 web.config에 다음과 같이 추가해 줍니다.

<system.serviceModel>

  <services>
    <service name="WebApplication1.TestService" behaviorConfiguration="TestServiceBehavior">
      <endpoint address="" binding="basicHttpBinding"
              bindingConfiguration="basicHttpBindingConfiguration"
              contract="WebApplication1.ITestService" />
    </service>
  </services>

  <bindings>
    <basicHttpBinding>
      <binding name="basicHttpBindingConfiguration">
        <security mode="TransportWithMessageCredential">
          <message clientCredentialType="UserName"/>
        </security>
      </binding>
    </basicHttpBinding>
  </bindings>

  <behaviors>

    <serviceBehaviors>

      <behavior name="TestServiceBehavior">
        <serviceCredentials>
          <userNameAuthentication userNamePasswordValidationMode="Custom"
                                  customUserNamePasswordValidatorType="UserNamePasswordAuth.DatabaseBasedValidator, UserNamePasswordAuth"/>
        </serviceCredentials>

        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>

    </serviceBehaviors>

  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

일단, 서버 측은 이것으로 완료되었습니다. IIS 서버에 배포하고 HTTPS 바인딩 설정과 자가 서명한 "SSL 인증서"도 할당해 줍니다.

basicHttpBinding_Custom_Auth_1.png

자, 이제 클라이언트 측 호출 코드인데요. 우선, 우리가 임의로 발급한 인증서이기 때문에 이에 대한 유효성 검사를 무시할 수 있도록 다음과 같은 코드를 넣어둡니다.

System.Net.ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);

"WCF 사용자 정의 인증 구현 예제"에서는 serviceCertificate를 자체적으로 지정하고 있었고 클라이언트 측에서는 역시 인증서에 대한 유효성 검사를 <authentication certificateValidationMode="None" /> 설정으로 무시를 했었는데요. HTTPS에 사용된 인증서의 유효성 검사에 대해서는 위와 같이 ServerCertificateValidationCallback을 재지정함으로써 가능합니다.

이후 코드는 예전의 것과 다르지 않습니다.

using (ChannelFactory<WebApplication1.ITestService> factory =
    new ChannelFactory<WebApplication1.ITestService>("BasicHttpBinding_ITestService"))
{
    factory.Credentials.UserName.UserName = "test";
    factory.Credentials.UserName.Password = "test";

    WebApplication1.ITestService svc = factory.CreateChannel();
    ICommunicationObject cn = svc as ICommunicationObject;

    try
    {
        svc.DoWork();
        cn.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        cn.Abort();
    }
}   

단지, "BasicHttpBinding_ITestService"로 지정한 app.config의 바인딩 설정만을 맞춰주면 되는데, 다음과 같이 security 노드의 일부 값과 address 값의 https 프로토콜을 사용하도록 변경합니다.

<system.serviceModel>
  <client>
    <endpoint address="https://...:4430/TestService.svc"
              binding="basicHttpBinding" 
              bindingConfiguration="BasicHttpBinding_ITestService" 
              contract="WebApplication1.ITestService" 
              name="BasicHttpBinding_ITestService"/>      
  </client>

  <bindings>
    <basicHttpBinding>
      <binding name="BasicHttpBinding_ITestService">
        <security mode="TransportWithMessageCredential">
          <message clientCredentialType="UserName"/>
        </security>
      </binding>
    </basicHttpBinding>

  </bindings>

</system.serviceModel>

이제, 실행하면 정상적으로 "test" / "test" 계정으로 인증되는 것을 확인할 수 있습니다.

첨부한 파일은 위의 내용을 포함하고 있습니다.




그런데, 원래 제가 이번 실습을 하려는 의도는 따로 있었습니다. 바로 아래의 글이 모델이었는데요.

Finally! Usernames over Transport Authentication in WCF
; http://www.leastprivilege.com/PermaLink.aspx?guid=b0ed39eb-01d9-4711-8d38-92d932e2e8c3

위의 글에서 다음과 같은 문구가 나오는데요.

You may say now - isn't that exactly what TransportWithMessageCredential is supposed to do? Not exactly - because this involves sending a basic WS-Security SOAP header inside of the message. I want simple HTTP basic auth....


언급된 것처럼, 다른 플랫폼과의 보다 자유로운 Interop이 이뤄지려면 SecurityMode == TransportWithMessageCredential 상태는 바람직하지 않습니다. 그래서 위의 글에서 설명한 대로 예제를 진행했었는데, (아울러, IIS 서버 측의 "Basic Authentication"을 활성화 시켜야 합니다.)

<bindings>
  <basicHttpBinding>
    <binding name="secureBasic">
      <security mode="Transport">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>

아쉽게도, 제 경우에는 customUserNamePasswordValidatorType에 지정된 사용자 정의 인증 모듈이 불려지지 않아서 다음과 같은 오류만 발생했습니다.

System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Basic'. The authentication header received from the server was 'Basic realm="..."'. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.


대신에, 지정된 대로 순수하게 Windows에 등록된 계정 정보를 Basic 인증에 넣어서 보내야만 정상적으로 인증이 되었습니다.

혹시, basicHttpBinding + security mode="Transport" + clientCredentialType="Basic"의 설정으로 사용자 정의 인증 모듈 호출에 성공하신 분이 있다면 소개 부탁드리겠습니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/27/2021]

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

비밀번호

댓글 작성자
 



2014-11-19 08시07분
[김영대] 정말 잘배웠습니다 감사드립니다.
IIS 에 WCF 서비스를 호스팅하고 wsHttpBinding을 이용하여

아래 예제
WCF 사용자 정의 인증 구현 예제
; http://www.sysnet.pe.kr/2/0/864

를 따라 해보았지만 클라이언트에서 인증을 하지못해

위 예제로 그대로 따라하되 바인딩은 wsHttpBinding 을 그대로 이용하였습니다 ( serviceCertificate 부분은 주석 처리 하고 IIS 설정으로 인증서 첨부하였습니다.)

제가 만든 인증서는 도메인명과 (?) 일치하지 않아서 그런지

https://localhost/test.svc 로 브라우저에서 접근하면 보안경고가 뜹니다.

하지만 가르쳐주신 예제처럼 클라이언트에 서비스 호출전에 아래 구문을 삽입하니 서비스 호출하는데 문제가 없었습니다
System.Net.ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);

이 구문은 처음 보는것인데 역할이 혹시 인증서 경고를 무시하고 넘어가는 기능인지 죄송하지만 질문드립니다.

감사합니다 정성태 시삽님


[guest]
2014-11-19 12시44분
음... 인증서 경고를 무시하고 넘어가는 것이 아니면... 혹시 어떤 이유가 또 있을 것으로 생각하시는 지가 궁금하군요. ^^
정성태

... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13232정성태1/27/20234856스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233786오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234143개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235157.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235254.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234948개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234673.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233904개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234264Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234470오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234144개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234372Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234470오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20234017Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233950VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234533디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234786디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236351Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235896.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235436오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235182기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235219웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234305Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234211Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20234184.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224455.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...