첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ WCF 사용자 정의 인증 사용하기

------------------------------------------------------------------------------------------------------------------------

TestSolution.zip


[TestServer 프로젝트]

 

ISimpleService.cs

 

 

using System.ServiceModel;

 

namespace TestServer

{

    /// <summary>

    /// 단순 서비스 인터페이스

    /// </summary>

    [ServiceContract]

    public interface ISimpleService

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

 

        #region 서버 시간 구하기 - GetServerTime()

 

        /// <summary>

        /// 서버 시간 구하기

        /// </summary>

        /// <returns>서버 시간</returns>

        [OperationContract]

        string GetServerTime();

 

        #endregion

    }

}

 

 

SimpleService.cs

 

 

using System;

 

namespace TestServer

{

    /// <summary>

    /// 단순 서비스

    /// </summary>

    public class SimpleService : ISimpleService

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 서버 시간 구하기 - GetServerTime()

 

        /// <summary>

        /// 서버 시간 구하기

        /// </summary>

        /// <returns>서버 시간</returns>

        public string GetServerTime()

        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

        }

 

        #endregion

    }

}

 

 

CustomUserNamePasswordValidator.cs

 

 

using System;

using System.IdentityModel.Selectors;

using System.ServiceModel;

 

namespace TestServer

{

    /// <summary>

    /// 커스텀 사용자명/패스워드 검사기

    /// </summary>

    public class CustomUserNamePasswordValidator : UserNamePasswordValidator

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 무결성 조사하기 - Validate(userName, password)

 

        /// <summary>

        /// 무결성 조사하기

        /// </summary>

        /// <param name="userName">사용자명</param>

        /// <param name="password">패스워드</param>

        public override void Validate(string userName, string password)

        {

            if(string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))

            {

                throw new ArgumentNullException();

            }

 

            if(!(userName == "홍길동" && password == "1234"))

            {

                throw new FaultException("사용자명 또는 패스워드가 일치하지 않습니다.");

            }

        }

 

        #endregion

    }

}

 

 

Program.cs

 

 

using System.ServiceModel;

using System;

 

namespace TestServer

{

    /// <summary>

    /// 프로그램

    /// </summary>

    class Program

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Static

        //////////////////////////////////////////////////////////////////////////////// Private

 

        #region 프로그램 시작하기 - Main()

 

        /// <summary>

        /// 프로그램 시작하기

        /// </summary>

        private static void Main()

        {

            using(ServiceHost serviceHost = new ServiceHost(typeof(SimpleService)))

            {

                serviceHost.Open();

 

                Console.WriteLine("서버가 시작되었습니다 : "DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

 

                Console.ReadKey(true);

            }

        }

 

        #endregion

    }

}

 

 

App.config

 

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <system.serviceModel>

        <behaviors>

            <serviceBehaviors>

                <behavior name="mexBehavior">

                    <serviceMetadata httpGetEnabled="true" />

                    <serviceDebug includeExceptionDetailInFaults="true" />

                    <serviceCredentials>

                        <serviceCertificate

                            findValue="WCFServer"

                            storeLocation="CurrentUser"

                            storeName="My"

                            x509FindType="FindBySubjectName" />

                        <userNameAuthentication

                            userNamePasswordValidationMode="Custom"

                            customUserNamePasswordValidatorType="TestServer.CustomUserNamePasswordValidator, TestServer" />

                    </serviceCredentials>

                </behavior>

            </serviceBehaviors>

        </behaviors>

        <bindings>

            <wsHttpBinding>

                <binding name="wsHttp">

                    <security mode="Message">

                        <message clientCredentialType="UserName" />

                    </security>

                </binding>

            </wsHttpBinding>

            <netTcpBinding>

                <binding name="netTcp">

                    <security mode="Message">

                        <message clientCredentialType="UserName" />

                    </security>

                </binding>

            </netTcpBinding>

        </bindings>

        <services>

            <service name="TestServer.SimpleService" behaviorConfiguration="mexBehavior">

                <endpoint

                    address="SimpleService"

                    binding="wsHttpBinding"

                    bindingConfiguration="wsHttp"

                    contract="TestServer.ISimpleService" />

                <endpoint

                    address="SimpleService"

                    binding="netTcpBinding"

                    bindingConfiguration="netTcp"

                    contract="TestServer.ISimpleService" />

                <host>

                    <baseAddresses>

                        <add baseAddress="http://localhost:8080" />

                        <add baseAddress="net.tcp://localhost:8090" />

                    </baseAddresses>

                </host>

            </service>

        </services>

    </system.serviceModel>

</configuration>

 

 

[TestClient 프로젝트]

 

MainForm.cs

 

 

using System;

using System.Windows.Forms;

 

using TestClient.SimpleService;

 

namespace TestClient

{

    /// <summary>

    /// 메인 폼

    /// </summary>

    public partial class MainForm : Form

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainForm()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainForm()

        {

            InitializeComponent();

 

            this.callButton.Click += callButton_Click;

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region 호출하기 버튼 클릭시 처리하기 - callButton_Click(sender, e)

 

        /// <summary>

        /// 호출하기 버튼 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void callButton_Click(object sender, EventArgs e)

        {

            using(SimpleServiceClient client = new SimpleServiceClient("WSHttpBinding_ISimpleService"))

            {

                client.ClientCredentials.UserName.UserName = "홍길동";

                client.ClientCredentials.UserName.Password = "1234";

 

                string serverTime = client.GetServerTime();

 

                MessageBox.Show(serverTime);

            }

        }

 

        #endregion

    }

}

 

 

App.config

 

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <startup>

        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />

    </startup>

    <system.serviceModel>

        <behaviors>

            <endpointBehaviors>

                <behavior name="customBehavior">

                    <clientCredentials>

                        <serviceCertificate>

                            <authentication certificateValidationMode="None" />

                        </serviceCertificate>

                    </clientCredentials>

                </behavior>

            </endpointBehaviors>

        </behaviors>

        <bindings>

            <netTcpBinding>

                <binding name="NetTcpBinding_ISimpleService">

                    <security mode="Message">

                        <message clientCredentialType="UserName" />

                    </security>

                </binding>

            </netTcpBinding>

            <wsHttpBinding>

                <binding name="WSHttpBinding_ISimpleService">

                    <security>

                        <message clientCredentialType="UserName" />

                    </security>

                </binding>

            </wsHttpBinding>

        </bindings>

        <client>

            <endpoint name="WSHttpBinding_ISimpleService" behaviorConfiguration="customBehavior"

                address="http://localhost:8080/SimpleService"

                binding="wsHttpBinding"

                bindingConfiguration="WSHttpBinding_ISimpleService"

                contract="SimpleService.ISimpleService">

                <identity>

                    <certificate encodedValue="AwAAAAEAAAAUAAAA/CZbeDwdDzqXgitnbganhdHxFZYgAAAAAQ

                                               AAALUBAAAwggGxMIIBX6ADAgECAhD7CT8Rmi9QuUeVFUSH7zL2

                                               MAkGBSsOAwIdBQAwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3kwHh

                                               cNMTgwMjEyMTMxNjUzWhcNMzkxMjMxMjM1OTU5WjAUMRIwEAYD

                                               VQQDEwlXQ0ZTZXJ2ZXIwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMI

                                               GJAoGBAMOswBkEswxKK9WuX8YbXJth3xF0FVKe2d+vBqZjRO+S

                                               QyE1yyE1pXgD1nmMPtwl3HyfSoKouuiaf2fc1Rnvp2vDaNeVSG

                                               72Tkq6wHfb2Uol47gXcCJ2UcN/7tdcm5St/tbBUvzgS9EibtWf

                                               YdtGSvez+VSd6N8a6R/ylzeBns7BAgMBAAGjSzBJMEcGA1UdAQ

                                               RAMD6AEBLkCS0GHR1PAI1hIdwWZGOhGDAWMRQwEgYDVQQDEwtS

                                               b290IEFnZW5jeYIQBjdsAKoAZIoRz7jUqlw19DAJBgUrDgMCHQ

                                               UAA0EANdZ6zWFh5pAERMhncGFyzxnHPHLmc1GmIcpbTidP6oa0

                                               VvsGltTVU1Vm3IBPPvHjKSsFMkUPyvF8GC5dveWGqw==" />

                </identity>

            </endpoint>

            <endpoint name="NetTcpBinding_ISimpleService" behaviorConfiguration="customBehavior"

                address="net.tcp://localhost:8090/SimpleService"

                binding="netTcpBinding"

                bindingConfiguration="NetTcpBinding_ISimpleService"

                contract="SimpleService.ISimpleService">

                <identity>

                    <certificate encodedValue="AwAAAAEAAAAUAAAA/CZbeDwdDzqXgitnbganhdHxFZYgAAAAAQ

                                               AAALUBAAAwggGxMIIBX6ADAgECAhD7CT8Rmi9QuUeVFUSH7zL2

                                               MAkGBSsOAwIdBQAwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3kwHh

                                               cNMTgwMjEyMTMxNjUzWhcNMzkxMjMxMjM1OTU5WjAUMRIwEAYD

                                               VQQDEwlXQ0ZTZXJ2ZXIwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMI

                                               GJAoGBAMOswBkEswxKK9WuX8YbXJth3xF0FVKe2d+vBqZjRO+S

                                               QyE1yyE1pXgD1nmMPtwl3HyfSoKouuiaf2fc1Rnvp2vDaNeVSG

                                               72Tkq6wHfb2Uol47gXcCJ2UcN/7tdcm5St/tbBUvzgS9EibtWf

                                               YdtGSvez+VSd6N8a6R/ylzeBns7BAgMBAAGjSzBJMEcGA1UdAQ

                                               RAMD6AEBLkCS0GHR1PAI1hIdwWZGOhGDAWMRQwEgYDVQQDEwtS

                                               b290IEFnZW5jeYIQBjdsAKoAZIoRz7jUqlw19DAJBgUrDgMCHQ

                                               UAA0EANdZ6zWFh5pAERMhncGFyzxnHPHLmc1GmIcpbTidP6oa0

                                               VvsGltTVU1Vm3IBPPvHjKSsFMkUPyvF8GC5dveWGqw==" />

                </identity>

            </endpoint>

        </client>

    </system.serviceModel>

</configuration>

 

------------------------------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요