이 샘플에서는 사용자 지정 토큰 인증자를 구현하는 방법을 보여 줍니다. WCF(Windows Communication Foundation)의 토큰 인증자는 메시지와 함께 사용되는 토큰의 유효성을 검사하고, 자체 일관성이 있는지 확인하고, 토큰과 연결된 ID를 인증하는 데 사용됩니다.
사용자 지정 토큰 인증자는 다음과 같은 다양한 경우에 유용합니다.
토큰과 연결된 기본 인증 메커니즘을 재정의하려는 경우
사용자 지정 토큰을 빌드하는 경우
이 샘플에서는 다음을 보여 줍니다.
클라이언트가 사용자 이름/암호 쌍을 사용하여 인증하는 방법입니다.
서버에서 사용자 지정 토큰 인증자를 사용하여 클라이언트 자격 증명의 유효성을 검사하는 방법입니다.
WCF 서비스 코드가 사용자 지정 토큰 인증자와 연결하는 방법
서버의 X.509 인증서를 사용하여 서버를 인증하는 방법
또한 이 샘플에서는 사용자 지정 토큰 인증 프로세스 후에 WCF에서 호출자의 ID에 액세스할 수 있는 방법을 보여 있습니다.
서비스는 App.config 구성 파일을 사용하여 정의된 서비스와 통신하기 위한 단일 엔드포인트를 노출합니다. 엔드포인트는 주소, 바인딩 및 계약으로 구성됩니다. 바인딩은 표준 wsHttpBinding
으로 구성되며, 보안 모드는 메시지로 설정됩니다. 기본 모드는 . wsHttpBinding
입니다. 이 샘플은 클라이언트 사용자 이름 인증을 사용하도록 표준을 wsHttpBinding
설정합니다. 서비스는 동작을 사용하여 serviceCredentials
서비스 인증서를 구성하기도 합니다. 이 securityCredentials
동작을 통해 서비스 인증서를 지정할 수 있습니다. 서비스 인증서는 클라이언트에서 서비스를 인증하고 메시지 보호를 제공하는 데 사용됩니다. 다음 구성은 다음 설정 지침에 설명된 대로 샘플 설치 중에 설치된 localhost 인증서를 참조합니다.
<system.serviceModel>
<services>
<service
name="Microsoft.ServiceModel.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<host>
<baseAddresses>
<!-- configure base address provided by host -->
<add baseAddress ="http://localhost:8000/servicemodelsamples/service" />
</baseAddresses>
</host>
<!-- use base address provided by host -->
<endpoint address=""
binding="wsHttpBinding"
bindingConfiguration="Binding1"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="False" />
<!--
The serviceCredentials behavior allows one to define a service certificate.
A service certificate is used by a client to authenticate the service and provide message protection.
This configuration references the "localhost" certificate installed during the setup instructions.
.... -->
<serviceCredentials>
<serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
클라이언트 엔드포인트 구성은 구성 이름, 서비스 엔드포인트의 절대 주소, 바인딩 및 계약으로 구성됩니다. 클라이언트 바인딩은 적절한 Mode
및 clientCredentialType
로 구성됩니다.
<system.serviceModel>
<client>
<endpoint name=""
address="http://localhost:8000/servicemodelsamples/service"
binding="wsHttpBinding"
bindingConfiguration="Binding1"
contract="Microsoft.ServiceModel.Samples.ICalculator">
</endpoint>
</client>
<bindings>
<wsHttpBinding>
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
클라이언트 구현은 사용할 사용자 이름과 암호를 설정합니다.
static void Main()
{
...
client.ClientCredentials.UserNamePassword.UserName = username;
client.ClientCredentials.UserNamePassword.Password = password;
...
}
사용자 지정 토큰 인증자
사용자 지정 토큰 인증자를 만들려면 다음 단계를 사용합니다.
사용자 지정 토큰 인증자를 작성합니다.
이 샘플은 사용자 이름에 유효한 전자 메일 형식이 있음을 확인하는 사용자 지정 토큰 인증자를 구현합니다. UserNameSecurityTokenAuthenticator를 파생시킵니다. 이 클래스에서 가장 중요한 메서드는 .입니다 ValidateUserNamePasswordCore(String, String). 이 메서드에서 인증자는 사용자 이름의 형식과 호스트 이름이 불량 도메인에서 온 것이 아닌지 유효성을 검사합니다. 두 조건이 모두 충족되면 사용자 이름 토큰 내에 저장된 정보를 나타내는 클레임을 제공하는 데 사용되는 인스턴스의 IAuthorizationPolicy 읽기 전용 컬렉션을 반환합니다.
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateUserNamePasswordCore(string userName, string password) { if (!ValidateUserNameFormat(userName)) throw new SecurityTokenValidationException("Incorrect UserName format"); ClaimSet claimSet = new DefaultClaimSet(ClaimSet.System, new Claim(ClaimTypes.Name, userName, Rights.PossessProperty)); List<IIdentity> identities = new List<IIdentity>(1); identities.Add(new GenericIdentity(userName)); List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1); policies.Add(new UnconditionalPolicy(ClaimSet.System, claimSet, DateTime.MaxValue.ToUniversalTime(), identities)); return policies.AsReadOnly(); }
사용자 지정 토큰 인증자가 반환하는 권한 부여 정책을 제공합니다.
이 샘플은 생성자에서 전달된 클레임 및 ID 집합을 반환하는 IAuthorizationPolicy 라는
UnconditionalPolicy
의 자체 구현을 제공합니다.class UnconditionalPolicy : IAuthorizationPolicy { String id = Guid.NewGuid().ToString(); ClaimSet issuer; ClaimSet issuance; DateTime expirationTime; IList<IIdentity> identities; public UnconditionalPolicy(ClaimSet issuer, ClaimSet issuance, DateTime expirationTime, IList<IIdentity> identities) { if (issuer == null) throw new ArgumentNullException("issuer"); if (issuance == null) throw new ArgumentNullException("issuance"); this.issuer = issuer; this.issuance = issuance; this.identities = identities; this.expirationTime = expirationTime; } public string Id { get { return this.id; } } public ClaimSet Issuer { get { return this.issuer; } } public DateTime ExpirationTime { get { return this.expirationTime; } } public bool Evaluate(EvaluationContext evaluationContext, ref object state) { evaluationContext.AddToTarget(this, this.issuance); if (this.identities != null) { object value; IList<IIdentity> contextIdentities; if (!evaluationContext.Properties.TryGetValue("Identities", out value)) { contextIdentities = new List<IIdentity>(this.identities.Count); evaluationContext.Properties.Add("Identities", contextIdentities); } else { contextIdentities = value as IList<IIdentity>; } foreach (IIdentity identity in this.identities) { contextIdentities.Add(identity); } } evaluationContext.RecordExpirationTime(this.expirationTime); return true; } }
사용자 지정 보안 토큰 관리자를 작성합니다.
SecurityTokenManager는 SecurityTokenAuthenticator 메서드에서 특정 SecurityTokenRequirement 개체에 대해
CreateSecurityTokenAuthenticator
을 생성하는 데 사용됩니다. 보안 토큰 관리자는 토큰 공급자 및 토큰 직렬 변환기를 만드는 데도 사용되지만 이 샘플에서는 다루지 않습니다. 이 샘플에서 사용자 지정 보안 토큰 관리자는 ServiceCredentialsSecurityTokenManager 클래스에서 상속하고, 전달된 토큰 요구 사항이 사용자 이름 인증자가 요청되었음을 나타낼 때 사용자 지정 사용자 이름 토큰 인증자를 반환할 수 있도록CreateSecurityTokenAuthenticator
메서드를 재정의합니다.public class MySecurityTokenManager : ServiceCredentialsSecurityTokenManager { MyUserNameCredential myUserNameCredential; public MySecurityTokenManager(MyUserNameCredential myUserNameCredential) : base(myUserNameCredential) { this.myUserNameCredential = myUserNameCredential; } public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver) { if (tokenRequirement.TokenType == SecurityTokenTypes.UserName) { outOfBandTokenResolver = null; return new MyTokenAuthenticator(); } else { return base.CreateSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver); } } }
사용자 지정 서비스 자격 증명을 작성합니다.
서비스 자격 증명 클래스는 서비스에 대해 구성된 자격 증명을 나타내고 토큰 인증자, 토큰 공급자 및 토큰 serializer를 가져오는 데 사용되는 보안 토큰 관리자를 만드는 데 사용됩니다.
public class MyUserNameCredential : ServiceCredentials { public MyUserNameCredential() : base() { } protected override ServiceCredentials CloneCore() { return new MyUserNameCredential(); } public override SecurityTokenManager CreateSecurityTokenManager() { return new MySecurityTokenManager(this); } }
사용자 지정 서비스 자격 증명을 사용하도록 서비스를 구성합니다.
서비스에서 사용자 지정 서비스 자격 증명을 사용하려면 기본 서비스 자격 증명에 이미 미리 구성된 서비스 인증서를 캡처한 후 기본 서비스 자격 증명 클래스를 삭제하고, 미리 구성된 서비스 인증서를 사용하고 이 새 서비스 자격 증명 인스턴스를 서비스 동작에 추가하도록 새 서비스 자격 증명 인스턴스를 구성합니다.
ServiceCredentials sc = serviceHost.Credentials; X509Certificate2 cert = sc.ServiceCertificate.Certificate; MyUserNameCredential serviceCredential = new MyUserNameCredential(); serviceCredential.ServiceCertificate.Certificate = cert; serviceHost.Description.Behaviors.Remove((typeof(ServiceCredentials))); serviceHost.Description.Behaviors.Add(serviceCredential);
호출자의 정보를 표시하려면 다음 코드와 같이 사용할 PrimaryIdentity 수 있습니다. Current 현재 호출자에 대한 클레임 정보를 포함합니다.
static void DisplayIdentityInformation()
{
Console.WriteLine("\t\tSecurity context identity : {0}",
ServiceSecurityContext.Current.PrimaryIdentity.Name);
return;
}
샘플을 실행하면 작업 요청 및 응답이 클라이언트 콘솔 창에 표시됩니다. 클라이언트 창에서 Enter 키를 눌러 클라이언트를 종료합니다.
Batch 파일 설정
이 샘플에 포함된 Setup.bat 일괄 처리 파일을 사용하면 서버 인증서 기반 보안이 필요한 자체 호스팅 애플리케이션을 실행하도록 관련 인증서를 사용하여 서버를 구성할 수 있습니다. 이 일괄 처리 파일은 컴퓨터 간 작동하거나 비호스팅 환경에서 작동하도록 수정해야 합니다.
다음은 적절한 구성에서 실행되도록 수정할 수 있도록 일괄 처리 파일의 다양한 섹션에 대한 간략한 개요를 제공합니다.
서버 인증서 만들기
Setup.bat 일괄 처리 파일의 다음 줄은 사용할 서버 인증서를 만듭니다. 변수는
%SERVER_NAME%
서버 이름을 지정합니다. 이 변수를 변경하여 사용자 고유의 서버 이름을 지정합니다. 이 일괄 처리 파일의 기본값은 localhost입니다.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
클라이언트의 신뢰할 수 있는 인증서 저장소에 서버 인증서 설치
Setup.bat 일괄 처리 파일의 다음 줄은 서버 인증서를 클라이언트에서 신뢰할 수 있는 사용자 저장소에 복사합니다. Makecert.exe 생성된 인증서는 클라이언트 시스템에서 암시적으로 신뢰할 수 없으므로 이 단계가 필요합니다. 클라이언트에서 신뢰할 수 있는 루트 인증서(예: Microsoft 발급 인증서)에 루트된 인증서가 이미 있는 경우 클라이언트 인증서 저장소를 서버 인증서로 채우는 이 단계는 필요하지 않습니다.
certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r CurrentUser -s TrustedPeople
비고
설치 일괄 처리 파일은 Windows SDK 명령 프롬프트에서 실행되도록 설계되었습니다. MSSDK 환경 변수는 SDK가 설치된 디렉터리를 가리킵니다. 이 환경 변수는 Windows SDK 명령 프롬프트 내에서 자동으로 설정됩니다.
샘플을 설정하고 빌드하려면
Windows Communication Foundation 샘플 에 대한One-Time 설정 절차를 수행했는지 확인합니다.
솔루션을 빌드하려면 Windows Communication Foundation 샘플 빌드의 지침을 따릅니다.
동일한 컴퓨터에서 샘플을 실행하려면
관리자 권한으로 열린 Visual Studio 명령 프롬프트 내의 샘플 설치 폴더에서 Setup.bat 실행합니다. 그러면 샘플을 실행하는 데 필요한 모든 인증서가 설치됩니다.
비고
Setup.bat 배치 파일은 Visual Studio 명령 프롬프트에서 실행되도록 설계되었습니다. Visual Studio 명령 프롬프트 내에 설정된 PATH 환경 변수는 Setup.bat 스크립트에 필요한 실행 파일이 포함된 디렉터리를 가리킵니다.
service\bin에서 service.exe 시작합니다.
\client\bin에서 client.exe 시작합니다. 클라이언트 활동은 클라이언트 콘솔 애플리케이션에 표시됩니다.
클라이언트와 서비스가 통신할 수 없는 경우 WCF 샘플대한 문제 해결 팁을 참조하세요.
컴퓨터에서 샘플을 실행하려면
서비스 컴퓨터에 서비스 이진 파일에 대한 디렉터리를 만듭니다.
서비스 프로그램 파일을 서비스 컴퓨터의 서비스 디렉터리에 복사합니다. 또한 서비스 컴퓨터에 Setup.bat 및 Cleanup.bat 파일을 복사합니다.
컴퓨터의 완전한 도메인 이름이 포함된 주체 이름을 가진 서버 인증서가 필요합니다. 이 새 인증서 이름을 반영하도록 서비스 App.config 파일을 업데이트해야 합니다.
%SERVER_NAME%
변수를 서비스가 실행될 컴퓨터의 완전히 자격이 있는 호스트 이름으로 설정하면, Setup.bat를 사용하여 하나를 만들 수 있습니다. setup.bat 파일은 관리자 권한으로 열린 Visual Studio용 개발자 명령 프롬프트에서 실행해야 합니다.서버 인증서를 클라이언트의 CurrentUser-TrustedPeople 저장소에 복사합니다. 클라이언트에서 신뢰할 수 있는 발급자에서 서버 인증서를 발급하는 경우를 제외하고는 이 작업을 수행할 필요가 없습니다.
서비스 컴퓨터의 App.config 파일에서 기본 주소의 값을 변경하여 localhost 대신 정규화된 컴퓨터 이름을 지정합니다.
서비스 컴퓨터에서 명령 프롬프트에서 service.exe 실행합니다.
언어별 폴더 아래의 \client\bin\ 폴더에서 클라이언트 컴퓨터로 클라이언트 프로그램 파일을 복사합니다.
클라이언트 컴퓨터의 Client.exe.config 파일에서 엔드포인트의 주소 값을 서비스의 새 주소와 일치하도록 변경합니다.
클라이언트 컴퓨터의 명령 프롬프트에서 Client.exe 시작합니다.
클라이언트와 서비스가 통신할 수 없는 경우 WCF 샘플대한 문제 해결 팁을 참조하세요.
샘플 후에 정리하기
- 샘플 실행이 완료되면 샘플 폴더에서 Cleanup.bat 실행합니다.