Monday 25 November 2013

Authenticate a service request based on username a nd password received

Steps for creating a secured service
  1. Create a blank solution; name it as wcf Security (not mandatory).
  2. Add two projects to it 1) Web application 2) wcf application.
  3. Add a service to wcf application and name.
  4. Add a method called “Dowork” and return a string.
public string DoWork()
{
return “Yes trying to do wcf authentication”;
}

Add a class to service application and name it as customvalidator.

public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void
Validate(string userName, string password)
{
// peform
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
if (!(userName == “test1″ && password == “1tset”) && !(userName == “test2″ && password == “2tset”))
{
throw new SecurityTokenException(“Unknown Username or Incorrect Password”);
}
}
}
}
  1. Inherit “UserNamePasswordValidator” this class.
  2. And override abstract method in the class. Use this class in service behavior.
  3. Add a new binding in web.config file of type ” wsHttpBinding” name the binding as your wish
  4. You can directly add this binding inside system.servicemodel .
<bindings><wsHttpBinding>
<binding name=”SampleBinding” closeTimeout=”00:10:00″ openTimeout=”00:10:00″ receiveTimeout=”00:10:00″ sendTimeout=”00:10:00″ bypassProxyOnLocal=”false” transactionFlow=”false” hostNameComparisonMode=”StrongWildcard” messageEncoding=”Text” textEncoding=”utf-8″ useDefaultWebProxy=”true” allowCookies=”false”>

<reliableSession ordered=”true” inactivityTimeout=”00:10:00″ enabled=”false” />
<security mode=”Message”>
<message clientCredentialType=”UserName”/>
</security>
</binding>
</wsHttpBinding>
</bindings>

Add behavior to your service

<behaviors>
<serviceBehaviors>
<behavior name=”Services.Products”>
<!– To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment –>
<serviceMetadata httpGetEnabled=”true” />
<!– To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information –>
<serviceDebug includeExceptionDetailInFaults=”true” />
<serviceCredentials>
<serviceCertificate findValue=”localhost” storeLocation=”LocalMachine”
storeName=”My” x509FindType=”FindBySubjectName” />
<userNameAuthentication userNamePasswordValidationMode=”Custom”
customUserNamePasswordValidatorType=”Services.SystemSecurityCustomValidator, Services” />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>


Add service configuration

<services>
<service name=”Services.Products” behaviorConfiguration=”Services.Products”>
<!– Service Endpoints –>
<endpoint address=”" binding=”wsHttpBinding” bindingConfiguration=”SampleBinding” contract=”Services.IProducts”>
<!– Upon deployment, the foll owing identity element should be removed or replaced to reflect the identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity automatically.  –>
<identity>
<dns value=”localhost” />
</identity>
</endpoint>
<endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange” />
</service>
</services>

  1. Now create a certificate on your machine.
  2. You can use free certificate providers like plural sight’s makecert.
  3. Download tool and run as admin.
  4. Now create a certificate using the tool. Make sure you are creating a certificate which you are using in service behavior.
  5. Add certificate in IIS and host both the applications in IIS
  6. And you are ready with service, let’s work on client application.
  7. Add a new form to web application.
  8. Add a button to the form and a label.
  9. Keep text empty for label.
  10. Now add service reference to application.
  11. On button click add this code.
TestClient testservice = null;
public Default()
{
testservice = new TestClient();
testservice.ClientCredentials.UserName.UserName = “ECC”;
testservice.ClientCredentials.UserName.Password = “ECC”;
testservice.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
System.ServiceModel.Security.X509CertificateValidationMode.Custom;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblText.Text = testservice.DoWork();
}
  1. You can also retrieve credentials from db instead of hardcode values.
  2. If credentials are correct label displays the text, else throws an error.
About Author
Rachna Bagwe works with Systems Plus and is working on Dot net technology projects. She can be contacted at: rachna.b@spluspl.com

1 comment:

  1. Is is possible to create Authenticate a service using ASP.NET Web Service?

    ReplyDelete