how can I create authenticating web service soap in c#

Question!

For connecting to the soap web service, I intend to authenticate my clients but I could not find any information on it. In my opinion, the sole method based on principals can be Soapheader. According to the explanations I read, I wrote my code as follows:

IService.cs
public interface IService
{
    [OperationContract]
    bool DoWork();
}

Service.cs
public class Service : IService
{
    public AuthHeader Authentication;


    [SoapHeader("Authentication", Required = true)]
    [WebMethod(Description = "Returns some sample data")]
    public bool DoWork()
    {
        if (Authentication.Username == "userName" &&
        Authentication.Password == "pwd")
        {
            //Do your thing
            return true;

        }
        else
        {
            //if authentication fails
            return false;
        }
    }
}

The main problem is that when I start the project, there is no parameter in the Header section of the method.

<s:envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:header>
    <action s:mustunderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService/DoWork</action>
</s:header>
<s:body>
    <dowork xmlns="http://tempuri.org/" />
</s:body>
</s:envelope>

Would you please let me know how I can get the username and password of the webservice from client? If youÂ’ve got any other way, please tell me. I appreciate your cooperation an advance.



Answers

I would start by including WCFExtras (https://wcfextras.codeplex.com/).

Then you can do the following:

1. Define AuthHeader-Class

[DataContract]
public class AuthHeader
{
    [DataMember]
    public string Username { get; set; }

    [DataMember]
    public string Password { get; set; }
}

2. Inside IService: Add [SoapHeaders] to your [ServiceContract] (SoapHeaders is available after including WCFExtras). Also add [SoapHeader...] to [OperationContract]

[ServiceContract]    
[SoapHeaders]
public interface IService
{
    [OperationContract]
    [WCFExtras.Soap.SoapHeader("AuthHeader", typeof(AuthHeader))]
    bool DoWork();
}

3. In Service.cs use SoapHeaderHelper (part of WCFExtras):

public class Service : IService
{
    [WebMethod(Description = "Returns some sample data")]
    public bool DoWork()
    {
        AuthHeader authentication = SoapHeaderHelper
By : exean


This video can help you solving your question :)
By: admin