Monday, October 10, 2011

Custom UserName-Password Validator in WCF Service

1-

public class MyCustomValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
//get from db or anywhere
            if (userName != "engin" && password != "dotnet")
            {
                throw new SecurityTokenException("Validation failed.");
            }
        }
    } 


2-In WebConfig
 <bindings>
      <basicHttpBinding>
        <binding name="basicBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic">transport>
          security>
        binding>
      basicHttpBinding>
    bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBeh">
          <serviceMetadata httpGetEnabled="true" />
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WcfServiceLibrary2.MyCustomValidator,WcfServiceLibrary2"/>
          serviceCredentials>
        behavior>
      serviceBehaviors>
    behaviors>
3-Finall write your code;
           WcfUserPassClient svc = new WcfUserPassClient();
            svc.ClientCredentials.UserName.UserName = "engin";
            svc.ClientCredentials.UserName.Password = "dotnet";
            string result = svc.DoWork();

No comments:

Post a Comment