WCF - webHttpBinding 윈도우 인증 구현 예제
지난번 이야기에 이어서.
WCF - webHttpBinding 구현 예제
; https://www.sysnet.pe.kr/2/0/833
질문하신 분의 상황에 맞게 인증을 넣어보았습니다. 이전 소스 코드에서 사용한 바인딩이 다음과 같은데,
using (ServiceHost serviceHost = new ServiceHost(typeof(CHelloWorld),
new Uri(baseAddress)))
{
ServiceEndpoint endpoint =
serviceHost.AddServiceEndpoint(typeof(IHelloWorld), new WebHttpBinding(), "");
endpoint.Behaviors.Add(new WebHttpBehavior());
serviceHost.Open();
...[생략]...
}
여기에 인증을 걸기 위해 다음과 같이 변경합니다.
WebHttpBinding binding = new WebHttpBinding();
binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(typeof(IHelloWorld), binding, "");
이제 WCF 서비스를 실행해 두고, 웹 브라우저로 접근하면 다음과 같이 인증 창을 묻게 됩니다.
[그림 1: 윈도우 인증]
물론, 정상적인 인증 정보를 입력하면 해당 웹 메서드가 실행되어 반환값을 보내줍니다.
WCF 클라이언트로도 확인해 볼까요? 같은 PC에서 테스트 하거나 또는 다른 PC인 경우라도 계정/암호가 동일하게 로그인했다면 다음과 같이 코드를 구성할 수 있습니다.
WebHttpBinding clntBinding = new WebHttpBinding();
clntBinding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
clntBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
using (ChannelFactory<IHelloWorld> factory = new ChannelFactory<IHelloWorld>(clntBinding,
new EndpointAddress(baseAddress)))
{
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
IHelloWorld proxy = factory.CreateChannel();
Console.WriteLine("Result of Get operation: {0}", proxy.GetDate("1990", "05", "01"));
}
만약, 명시적으로 다른 계정이라면 다음과 같이 반드시 계정 정보를 주어야 합니다.
using (ChannelFactory<IHelloWorld> factory = new ChannelFactory<IHelloWorld>(clntBinding,
new EndpointAddress(baseAddress)))
{
factory.Credentials.Windows.ClientCredential = new NetworkCredential("[계정]", "[암호]");
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
IHelloWorld proxy = factory.CreateChannel();
Console.WriteLine("Result of Get operation: {0}", proxy.GetDate("1990", "05", "01"));
}
HttpWebRequest로도 해볼까요? 역시 같은 PC이거나, 다른 컴퓨터에서 로그인 정보가 같은 경우에는 다음과 같이 코딩을 하고,
static void Main(string[] args)
{
string baseAddress = "http://192.168.0.55:9091/HelloService";
string reqAddress = string.Format("{0}/date/1990/05/05", baseAddress);
HttpWebRequest req = WebRequest.Create(reqAddress) as HttpWebRequest;
req.UseDefaultCredentials = true;
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string text = sr.ReadToEnd();
Console.WriteLine(text);
}
만약, 명시적으로 계정을 지정해야 한다면 WCF와 유사하게 다음과 같이 마무리 지을 수 있습니다.
HttpWebRequest req = WebRequest.Create(reqAddress) as HttpWebRequest;
//req.UseDefaultCredentials = true;
req.Credentials = new NetworkCredential("계정", "암호");
첨부한 파일은 테스트가 바로 가능한 프로젝트 소스 코드를 포함하고 있습니다.
[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]