Microsoft MVP성태의 닷넷 이야기
.NET Framework: 172. WCF - webHttpBinding 윈도우 인증 구현 예제 [링크 복사], [링크+제목 복사],
조회: 25765
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

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_webhttpbinding_windows_credential_1.png

물론, 정상적인 인증 정보를 입력하면 해당 웹 메서드가 실행되어 반환값을 보내줍니다.




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("계정", "암호");

첨부한 파일은 테스트가 바로 가능한 프로젝트 소스 코드를 포함하고 있습니다.






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

[연관 글]






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

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

비밀번호

댓글 작성자
 



2010-01-25 06시49분
[꼭지(서정수)] 아이구.. 케빈님 이렇게 글까지 작성을 해주시구.. 고맙습니다.
일단 첨부된 파일로 확인을 해보도록 하겠습니다.
다시 한 번 감사의 말씀 드립니다.

회원가입 하고픈데.. 시간나실때 꼭 되게 해주세요..^^
[guest]
2010-01-26 12시23분
참.. 그리고 회원가입은... ^^; 별다르게 혜택이 없기 때문에 굳이 하실 필요는 없습니다.
안 그래도 웹 사이트를 좀 내부적으로 손을 봐야 하는데... 가끔 남는 시간마저도 서정수님처럼 꼭 환경 구성이 필요한 질문들을 하시는 분들 때문에 시간을 못 내고 있습니다.

암튼, 꼭 손을 보도록 하겠습니다. ^^
kevin25
2010-01-26 11시51분
[꼭지] ^^
네네.. 알겠습니다.
가끔 남는 시간을 저에게 할애해주셔서 너무 감사드립니다.
시간 쿠폰이라는게 있다면, 좀 전해 드리고 싶네요.
암쪼록 정성스런 답변에 감사드립니다.
오늘 하루도 많이 웃으시구요. ^^
[guest]

... 151  152  153  154  155  156  157  158  159  160  161  162  [163]  164  165  ...
NoWriterDateCnt.TitleFile(s)
969정성태12/31/201040323VC++: 45. Winsock 2 Layered Service Provider - Visual Studio 2010용 프로젝트 [1]파일 다운로드1
968정성태12/30/201026560개발 환경 구성: 94. 개발자가 선택할 수 있는 윈도우에서의 네트워크 프로그래밍 기술 [2]
967정성태12/27/201028345.NET Framework: 197. .NET 코드 - 단일 Process 실행파일 다운로드1
966정성태12/26/201026313.NET Framework: 196. .NET 코드 - 창 흔드는 효과파일 다운로드1
965정성태12/25/201027791개발 환경 구성: 93. MSBuild를 이용한 닷넷 응용프로그램의 다중 어셈블리 출력 빌드파일 다운로드1
964정성태12/21/2010142958개발 환경 구성: 92. 윈도우 서버 환경에서, 최대 생성 가능한 소켓(socket) 연결 수는 얼마일까? [14]
963정성태12/13/201027838개발 환경 구성: 91. MSBuild를 이용한 닷넷 응용프로그램의 플랫폼(x86/x64)별 빌드 [2]파일 다운로드1
962정성태12/10/201022745오류 유형: 110. GAC 등록 - Failure adding assembly to the cache: Invalid file or assembly name.
961정성태12/10/201099751개발 환경 구성: 90. 닷넷에서 접근해보는 PostgreSQL DB [5]
960정성태12/8/201045046.NET Framework: 195. .NET에서 코어(Core) 관련 CPU 정보 알아내는 방법파일 다운로드1
959정성태12/8/201031862.NET Framework: 194. Facebook 연동 - API Error Description: Invalid OAuth 2.0 Access Token
958정성태12/7/201028845개발 환경 구성: 89. 배치(batch) 파일에서 또 다른 배치 파일을 동기 방식으로 실행 및 반환값 얻기 [2]
957정성태12/6/201031578디버깅 기술: 31. Windbg - Visual Studio 디버그 상태에서 종료해 버리는 응용 프로그램 [3]
953정성태11/28/201036830.NET Framework: 193. 페이스북(Facebook) 계정으로 로그인하는 C# 웹 사이트 제작 [5]
952정성태11/25/201025254.NET Framework: 192. GC의 부하는 상대적인 것! [4]
950정성태11/18/201076631.NET Framework: 191. ClickOnce - 관리자 권한 상승하는 방법 [17]파일 다운로드2
954정성태11/29/201048631    답변글 .NET Framework: 191.1. [답변] 클릭원스 - 요청한 작업을 수행하려면 권한 상승이 필요합니다. (Exception from HRESULT: 0x800702E4) [2]
949정성태11/16/201027165오류 유형: 109. System.ServiceModel.Security.SecurityNegotiationException
948정성태11/16/201035955.NET Framework: 190. 트위터 계정으로 로그인하는 C# 웹 사이트 제작 [7]파일 다운로드1
947정성태11/14/201041645.NET Framework: 189. Mono Cecil로 만들어 보는 .NET Decompiler [1]파일 다운로드1
946정성태11/11/201041463.NET Framework: 188. .NET 64비트 응용 프로그램에서 왜 (2GB) OutOfMemoryException 예외가 발생할까? [1]파일 다운로드1
945정성태11/11/201025006VC++: 44. C++/CLI 컴파일 오류 - error C4368: mixed types are not supported
944정성태11/11/201031464VC++: 43. C++/CLI 컴파일 오류 - error C2872: 'IServiceProvider' : ambiguous symbol could be ...
943정성태11/8/201030580디버깅 기술: 30. windbg ".loadby sos" 명령어 [2]
942정성태11/7/201042176.NET Framework: 187. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 [7]파일 다운로드3
941정성태11/6/201025089.NET Framework: 186. windbg로 확인하는 .NET CLR LCG 메서드(DynamicMethod) [1]파일 다운로드1
... 151  152  153  154  155  156  157  158  159  160  161  162  [163]  164  165  ...