메시지 보안 인증서
MessageSecurity 샘플 클라이언트에 대해 X.509 v3 인증서 인증으로 WS-Security 사용하고 서버의 X.509 v3 인증서를 사용하여 서버 인증을 요구하는 애플리케이션을 구현하는 방법을 보여 줍니다. 이 샘플에서는 클라이언트와 서버 간의 모든 애플리케이션 메시지가 서명되고 암호화되도록 기본 설정을 사용합니다. 이 샘플은 WSHttpBinding 기반으로 하며 클라이언트 콘솔 프로그램 및 IIS(인터넷 정보 서비스)에서 호스트하는 서비스 라이브러리로 구성됩니다. 서비스는 요청-회신 통신 패턴을 정의하는 계약을 구현합니다.
메모
이 샘플에 대한 설치 절차 및 빌드 지침은 이 항목의 끝에 있습니다.
이 샘플에서는 다음 샘플 코드와 같이 구성을 사용하여 인증을 제어하고 보안 컨텍스트에서 호출자의 ID를 가져오는 방법을 보여 줍니다.
public class CalculatorService : ICalculator
{
public string GetCallerIdentity()
{
// The client certificate is not mapped to a Windows identity by default.
// ServiceSecurityContext.PrimaryIdentity is populated based on the information
// in the certificate that the client used to authenticate itself to the service.
return ServiceSecurityContext.Current.PrimaryIdentity.Name;
}
...
}
서비스는 서비스와 통신하기 위한 엔드포인트 하나와 구성 파일(Web.config)을 사용하여 정의된 WS-MetadataExchange 프로토콜을 사용하여 서비스의 WSDL 문서를 노출하기 위한 엔드포인트 하나를 노출합니다. 엔드포인트는 주소, 바인딩 및 계약으로 구성됩니다. 바인딩은 기본적으로 메시지 보안을 사용하는 표준 <wsHttpBinding> 요소로 구성됩니다. 이 샘플에서는 clientCredentialType
특성을 인증서로 설정하여 클라이언트 인증을 요구합니다.
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="wsHttpBinding"/>
</protocolMapping>
<bindings>
<wsHttpBinding>
<!--
This configuration defines the security mode as Message and
the clientCredentialType as Certificate.
-->
<binding>
<security mode ="Message">
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-->
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
<!--
The serviceCredentials behavior allows one to define a service certificate.
A service certificate is used by the service to authenticate itself to its clients and to provide message protection.
This configuration references the "localhost" certificate installed during the setup instructions.
-->
<serviceCredentials>
<serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
<clientCertificate>
<!--
Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
is in the user's Trusted People store, then it will be trusted without performing a
validation of the certificate's issuer chain. This setting is used here for convenience so that the
sample can be run without having to have certificates issued by a certification authority (CA).
This setting is less secure than the default, ChainTrust. The security implications of this
setting should be carefully considered before using PeerOrChainTrust in production code.
-->
<authentication certificateValidationMode="PeerOrChainTrust" />
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
이 동작은 클라이언트가 서비스를 인증할 때 사용되는 서비스의 자격 증명을 지정합니다. 서버 인증서 주체 이름은 <serviceCredentials> 요소의 findValue
특성에 지정됩니다.
<!--For debugging purposes, set the includeExceptionDetailInFaults attribute to true.-->
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
<!--
The serviceCredentials behavior allows one to define a service certificate.
A service certificate is used by the service to authenticate itself to its clients and to provide message protection.
This configuration references the "localhost" certificate installed during the setup instructions.
-->
<serviceCredentials>
<serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
<clientCertificate>
<!--
Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
is in the user's Trusted People store, then it will be trusted without performing a
validation of the certificate's issuer chain. This setting is used here for convenience so that the
sample can be run without having to have certificates issued by a certification authority (CA).
This setting is less secure than the default, ChainTrust. The security implications of this
setting should be carefully considered before using PeerOrChainTrust in production code.
-->
<authentication certificateValidationMode="PeerOrChainTrust" />
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
클라이언트 엔드포인트 구성은 서비스 엔드포인트, 바인딩 및 계약에 대한 절대 주소로 구성됩니다. 클라이언트 바인딩은 적절한 보안 모드 및 인증 모드로 구성됩니다. 컴퓨터 간 시나리오에서 실행하는 경우 서비스 엔드포인트 주소가 그에 따라 변경되었는지 확인합니다.
<system.serviceModel>
<client>
<!-- Use a behavior to configure the client certificate to present to the service. -->
<endpoint address="http://localhost/servicemodelsamples/service.svc" binding="wsHttpBinding" bindingConfiguration="Binding1" behaviorConfiguration="ClientCertificateBehavior" contract="Microsoft.Samples.Certificate.ICalculator"/>
</client>
<bindings>
<wsHttpBinding>
<!--
This configuration defines the security mode as Message and
the clientCredentialType as Certificate.
-->
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
...
</system.serviceModel>
클라이언트 구현은 구성 파일 또는 코드를 통해 사용할 인증서를 설정할 수 있습니다. 다음 샘플에서는 구성 파일에서 사용할 인증서를 설정하는 방법을 보여줍니다.
<system.serviceModel>
...
<behaviors>
<endpointBehaviors>
<behavior name="ClientCertificateBehavior">
<!--
The clientCredentials behavior allows one to define a certificate to present to a service.
A certificate is used by a client to authenticate itself to the service and provide message integrity.
This configuration references the "client.com" certificate installed during the setup instructions.
-->
<clientCredentials>
<clientCertificate findValue="client.com" storeLocation="CurrentUser" storeName="My" x509FindType="FindBySubjectName"/>
<serviceCertificate>
<!--
Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
is in the user's Trusted People store, then it will be trusted without performing a
validation of the certificate's issuer chain. This setting is used here for convenience so that the
sample can be run without having to have certificates issued by a certificate authority (CA).
This setting is less secure than the default, ChainTrust. The security implications of this
setting should be carefully considered before using PeerOrChainTrust in production code.
-->
<authentication certificateValidationMode="PeerOrChainTrust"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
다음 샘플에서는 프로그램에서 서비스를 호출하는 방법을 보여 줍니다.
// Create a client.
CalculatorClient client = new CalculatorClient();
// Call the GetCallerIdentity service operation.
Console.WriteLine(client.GetCallerIdentity());
...
//Closing the client gracefully closes the connection and cleans up resources.
client.Close();
샘플을 실행하면 작업 요청 및 응답이 클라이언트 콘솔 창에 표시됩니다. 클라이언트 창에서 Enter 키를 눌러 클라이언트를 종료합니다.
CN=client.com
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Press <ENTER> to terminate client.
Message Security 샘플에 포함된 Setup.bat 일괄 처리 파일을 사용하면 인증서 기반 보안이 필요한 호스트된 애플리케이션을 실행하도록 관련 인증서가 있는 클라이언트 및 서버를 구성할 수 있습니다. 일괄 처리 파일은 세 가지 모드로 실행할 수 있습니다. Visual Studio용 개발자 명령 프롬프트에서 단일 컴퓨터 모드로 실행하려면 setup.bat를 입력하십시오. 서비스 모드로 실행하려면 setup.bat 서비스를 입력하십시오. 클라이언트 모드로 실행하려면 setup.bat 클라이언트을 입력하십시오. 컴퓨터에서 샘플을 실행할 때 클라이언트 및 서버 모드를 사용합니다. 자세한 내용은 이 항목의 끝부분에 있는 설치 절차를 참조하세요. 다음은 적절한 구성에서 실행되도록 수정할 수 있도록 일괄 처리 파일의 여러 섹션에 대한 간략한 개요를 제공합니다.
클라이언트 인증서 만들기
일괄 처리 파일의 다음 줄은 클라이언트 인증서를 만듭니다. 지정된 클라이언트 이름은 만든 인증서의 주체 이름에 사용됩니다. 인증서는
My
저장소에CurrentUser
저장소 위치에서 저장됩니다.echo ************ echo making client cert echo ************ makecert.exe -sr CurrentUser -ss MY -a sha1 -n CN=%CLIENT_NAME% -sky exchange -pe
서버의 신뢰할 수 있는 인증서 저장소에 클라이언트 인증서 설치
일괄 처리 파일의 다음 줄은 서버가 관련 신뢰 또는 신뢰 없음 결정을 내릴 수 있도록 클라이언트 인증서를 서버의 TrustedPeople 저장소에 복사합니다. TrustedPeople 저장소에 설치된 인증서가 WCF(Windows Communication Foundation) 서비스에서 신뢰할 수 있도록 하려면 클라이언트 인증서 유효성 검사 모드를
PeerOrChainTrust
또는PeerTrust
설정해야 합니다. 구성 파일을 사용하여 이 작업을 수행하는 방법을 알아보려면 이전 서비스 구성 샘플을 참조하세요.echo ************ echo copying client cert to server's LocalMachine store echo ************ certmgr.exe -add -r CurrentUser -s My -c -n %CLIENT_NAME% -r LocalMachine -s TrustedPeople
서버 인증서 만들기
Setup.bat 일괄 처리 파일의 다음 줄은 사용할 서버 인증서를 만듭니다.
echo ************ echo Server cert setup starting echo %SERVER_NAME% echo ************ echo making server cert echo ************ makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=%SERVER_NAME% -sky exchange -pe
%SERVER_NAME% 변수는 서버 이름을 지정합니다. 인증서는 LocalMachine 저장소에 저장됩니다. Setup.bat 일괄 처리 파일이 서비스 인수(예: setup.bat 서비스)로 실행되는 경우 %SERVER_NAME% 컴퓨터의 정규화된 도메인 이름을 포함합니다. 그렇지 않으면 기본적으로 localhost로 설정됩니다.
클라이언트의 신뢰할 수 있는 인증서 저장소에 서버 인증서 설치
다음 줄은 서버 인증서를 클라이언트에서 신뢰할 수 있는 사용자 저장소에 복사합니다. Makecert.exe 생성된 인증서는 클라이언트 시스템에서 암시적으로 신뢰할 수 없으므로 이 단계가 필요합니다. 클라이언트에서 신뢰할 수 있는 루트 인증서(예: Microsoft 발급 인증서)에 루트된 인증서가 이미 있는 경우 클라이언트 인증서 저장소를 서버 인증서로 채우는 이 단계는 필요하지 않습니다.
certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r CurrentUser -s TrustedPeople
인증서의 프라이빗 키에 대한 사용 권한 부여
Setup.bat 파일의 다음 줄은 LocalMachine 저장소에 저장된 서버 인증서를 ASP.NET 작업자 프로세스 계정에 액세스할 수 있도록 합니다.
echo ************ echo setting privileges on server certificates echo ************ for /F "delims=" %%i in ('"%ProgramFiles%\ServiceModelSampleTools\FindPrivateKey.exe" My LocalMachine -n CN^=%SERVER_NAME% -a') do set PRIVATE_KEY_FILE=%%i set WP_ACCOUNT=NT AUTHORITY\NETWORK SERVICE (ver | findstr /C:"5.1") && set WP_ACCOUNT=%COMPUTERNAME%\ASPNET echo Y|cacls.exe "%PRIVATE_KEY_FILE%" /E /G "%WP_ACCOUNT%":R iisreset
메모
미국 이외의 영어 버전 Windows를 사용하는 경우, Setup.bat 파일을 편집하고 "NT AUTHORITY\NETWORK SERVICE" 계정 이름을 해당 지역의 이름으로 바꿔야 합니다.
메모
이 일괄 처리 파일에 사용되는 도구는 C:\Program Files\Microsoft Visual Studio 8\Common7\tools 또는 C:\Program Files\Microsoft SDKs\Windows\v6.0\bin에 있습니다. 이러한 디렉터리 중 하나가 시스템 경로에 있어야 합니다. Visual Studio를 설치한 경우 경로에서 이 디렉터리를 가져오는 가장 쉬운 방법은 Visual Studio용 개발자 명령 프롬프트를 여는 것입니다. 시작을 클릭한 다음 모든 프로그램, Visual Studio 2012, 도구를 선택합니다. 이 명령 프롬프트에는 이미 구성된 적절한 경로가 있습니다. 그렇지 않으면 경로에 적절한 디렉터리를 수동으로 추가해야 합니다.
샘플을 설정, 빌드 및 실행하려면
Windows Communication Foundation 샘플 을 위한,One-Time 설치 절차를 수행했는지 확인합니다.
솔루션의 C# 또는 Visual Basic .NET 버전을 빌드하려면 Windows Communication Foundation 샘플빌드의 지침을 따릅니다.
동일한 컴퓨터에서 샘플을 실행하려면
관리자 권한으로 Visual Studio용 개발자 명령 프롬프트를 열고 샘플 설치 폴더에서 Setup.bat 실행합니다. 그러면 샘플을 실행하는 데 필요한 모든 인증서가 설치됩니다.
메모
Setup.bat 배치 파일은 Visual Studio용 개발자 명령 프롬프트에서 실행되도록 설계되었습니다. 경로 환경 변수가 SDK가 설치된 디렉터리를 가리킵니다. 이 환경 변수는 Visual Studio용 개발자 명령 프롬프트(2010) 내에서 자동으로 설정됩니다.
주소
http://localhost/servicemodelsamples/service.svc
입력하여 브라우저를 사용하여 서비스에 대한 액세스를 확인합니다.\client\bin에서 Client.exe 시작합니다. 클라이언트 활동은 클라이언트 콘솔 애플리케이션에 표시됩니다.
클라이언트와 서비스가 통신할 수 없는 경우 WCF 샘플대한 문제 해결 팁을 참조하세요.
컴퓨터에서 샘플을 실행하려면
서비스 컴퓨터에서 디렉터리를 만듭니다. IIS(인터넷 정보 서비스) 관리 도구를 사용하여 이 디렉터리에 대한 servicemodelsamples라는 가상 애플리케이션을 만듭니다.
\inetpub\wwwroot\servicemodelsamples의 서비스 프로그램 파일을 서비스 컴퓨터의 가상 디렉터리에 복사합니다. \bin 하위 디렉터리의 파일을 복사해야 합니다. 또한 Setup.bat, Cleanup.bat및 ImportClientCert.bat 파일을 서비스 컴퓨터에 복사합니다.
클라이언트 컴퓨터에 클라이언트 이진 파일에 대한 디렉터리를 만듭니다.
클라이언트 프로그램 파일을 클라이언트 컴퓨터의 클라이언트 디렉터리에 복사합니다. 또한 Setup.bat, Cleanup.bat및 ImportServiceCert.bat 파일을 클라이언트에 복사합니다.
서버에서 관리자 권한으로 Visual Studio용 개발자 명령 프롬프트에서 setup.bat 서비스 실행합니다. 서비스 인수를 사용하여 setup.bat 실행하면 컴퓨터의 정규화된 도메인 이름이 있는 서비스 인증서가 만들어지고 서비스 인증서를 Service.cer 파일로 내보냅니다.
Web.config을(를) 편집하여 컴퓨터의 정규화된 도메인 이름과 동일한 새 인증서 이름을 <serviceCertificate>의
findValue
특성에 반영합니다.서비스 디렉터리에서 클라이언트 컴퓨터의 클라이언트 디렉터리로 Service.cer 파일을 복사합니다.
클라이언트에서 관리자 권한으로 Visual Studio용 개발자 명령 프롬프트에서 setup.bat 클라이언트 실행합니다. 클라이언트 인수를 사용하여 setup.bat 실행하면 client.com 클라이언트 인증서가 만들어지고 클라이언트 인증서가 Client.cer 파일로 내보냅니다.
클라이언트 컴퓨터의 Client.exe.config 파일에서 엔드포인트의 주소 값을 서비스의 새 주소와 일치하도록 변경합니다. localhost를 서버의 정규화된 도메인 이름으로 바꿔서 이 작업을 수행합니다.
클라이언트 디렉터리에서 서버의 서비스 디렉터리로 Client.cer 파일을 복사합니다.
클라이언트에서 관리자 권한으로 Visual Studio용 개발자 명령 프롬프트에서 ImportServiceCert.bat 실행합니다. 그러면 서비스 인증서가 Service.cer 파일에서 CurrentUser - TrustedPeople 저장소로 가져옵니다.
서버에서 관리자 권한으로 Visual Studio용 개발자 명령 프롬프트에서 ImportClientCert.bat 실행합니다. 그러면 클라이언트 인증서가 Client.cer 파일에서 LocalMachine - TrustedPeople 저장소로 가져옵니다.
클라이언트 컴퓨터의 명령 프롬프트 창에서 Client.exe 시작합니다. 클라이언트와 서비스가 통신할 수 없는 경우 WCF 샘플대한 문제 해결 팁을 참조하세요.
샘플 후에 정리하기
샘플 실행을 완료한 후 샘플 폴더에서 Cleanup.bat 실행합니다.
메모
이 스크립트는 컴퓨터에서 이 샘플을 실행할 때 클라이언트에서 서비스 인증서를 제거하지 않습니다. 컴퓨터에서 인증서를 사용하는 WCF(Windows Communication Foundation) 샘플을 실행한 경우 CurrentUser - TrustedPeople 저장소에 설치된 서비스 인증서를 지워야 합니다. 이렇게 하려면 다음 명령을 사용합니다.
certmgr -del -r CurrentUser -s TrustedPeople -c -n <Fully Qualified Server Machine Name>
예를 들면certmgr -del -r CurrentUser -s TrustedPeople -c -n server1.contoso.com
.