Steps for creating a secured service
- Create a blank solution; name it as wcf Security (not mandatory).
- Add two projects to it 1) Web application 2) wcf application.
- Add a service to wcf application and name.
- 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”);
}
}
}
}
{
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”);
}
}
}
}
- Inherit “UserNamePasswordValidator” this class.
- And override abstract method in the class. Use this class in service behavior.
- Add a new binding in web.config file of type ” wsHttpBinding” name the binding as your wish
- 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>
<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>
<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>
<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>
- Now create a certificate on your machine.
- You can use free certificate providers like plural sight’s makecert.
- Download tool and run as admin.
- Now create a certificate using the tool. Make sure you are creating a certificate which you are using in service behavior.
- Add certificate in IIS and host both the applications in IIS
- And you are ready with service, let’s work on client application.
- Add a new form to web application.
- Add a button to the form and a label.
- Keep text empty for label.
- Now add service reference to application.
- 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();
}
- You can also retrieve credentials from db instead of hardcode values.
- 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
Rachna Bagwe works with Systems Plus and is working on Dot net technology projects. She can be contacted at: rachna.b@spluspl.com
Is is possible to create Authenticate a service using ASP.NET Web Service?
ReplyDelete