Authenticate .NET web service with custom SOAP Header

Introduction

Many of us want ot secure the calls to our web services, right?

There are so many ways to do this, one of them is to use custom SOAP header.

Using this method we simply add a required SOAP header to our web services calls.

We embed the SOAP header into our message and validate its contents on the server.

If the SOAP header validation done successfully, the web server sends the web service response to the consumer.

Pretty simple, right?

Using the code

Now let’s see how to do this in visual studio:

/// 
/// Summary description for SOAPHeaderService
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(Name = "TestService",ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SOAPHeaderService : System.Web.Services.WebService
{
    public SOAPHeaderService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

Notice that the “WebServiceBinding” attribute has the “Name” argument set to “TestService”, I’ll explain this later.

Now, I write the custom SOAP header that I want to include in the SOAP message. To do this I’ll create a class inherited from “System.Web.Services.Protocols.SoapHeader” , and I’ll but the required properties in it.

public class UserCredentials : System.Web.Services.Protocols.SoapHeader
{
    public string userName;
    public string password;
}

Let’s add instance from that header in our service:

public class SOAPHeaderService : System.Web.Services.WebService
{
    // Visual studio will append a "UserCredentialsValue" property to the proxy class
    public UserCredentials consumer;

Note that the visual studio will create a property in web service proxy called “UserCredentialsValue” which will map the “consumer” public property in the web service.

Now we had to write a “Web Method” that uses that header in messaging.

[WebMethod]
    [SoapDocumentMethod(Binding = "TestService")]
    [SoapHeader("consumer",Required=true)]
    public string GetBalance()
    {
        if (checkConsumer())
            return consumer.userName + " had 10000000 credit";
        else
            return "Error in authentication";
    }

    private bool checkConsumer()
    {
        // In this method you can check the username and password 
        // with your database or something
        // You could also encrypt the password for more security
        if (consumer != null)
        {
            if (consumer.userName == "Ahmed" && consumer.password == "1234")
                return true;
            else
                return false;
        }
        else
            return false;
    }

Note that I have added the “Binding” value to that I had used in declaring my service.

Also I declared the SOAP header that method will require when called, as long as declaring it with required.

Now, the only thing is remaining is to call the service with the SOAP header:

SOAPHeaderService.SOAPHeaderService service = new SOAPHeaderService.SOAPHeaderService();
SOAPHeaderService.UserCredentials user = new SOAPHeaderService.UserCredentials();

  user.userName = "Ahmed";
  user.password = "1234";

 service.UserCredentialsValue = user;

 Console.WriteLine(service.GetBalance());

We just get reference to the service and the SOAP header, assign the SOAP header properties, attach it with the SOAP message and then make our call to the web method.

This is the console result after calling the service with username = “Ahmed” and password = “1234”

Right.JPG

This one with other data:

error.JPG

Points of Interest

Securing their web services is a thing that many developers ignore while they are working; they relay that on that is a difficult and nasty task.

In the fact securing web service is all about understand the messaging layer and the protocols, you just need to go a little more deep and then you will find it is a very simple task.

I’ll post ISA about the other techniques to secure web services.

 

 

Server Side:

/WebServices/App_Code

 

 

using System;

using System.Web;

using System.Collections;

using System.Web.Services;

using System.Web.Services.Protocols;





/// <summary>

/// Summary description for SOAPHeaderService

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(Name = "TestService",ConformsTo = WsiProfiles.BasicProfile1_1)]

public class SOAPHeaderService : System.Web.Services.WebService

{

    // Visual studio will append a "UserCredentialsValue" property to the proxy class

    public UserCredentials consumer;



    public SOAPHeaderService()

    {

        //Uncomment the following line if using designed components 

        //InitializeComponent(); 

    }



    [WebMethod]

    [SoapDocumentMethod(Binding = "TestService")]

    [SoapHeader("consumer",Required=true)]

    public string GetBalance()

    {

        if (checkConsumer())

            return consumer.userName + " had 10000000 credit";

        else

            return "Error in authentication";

    }



    private bool checkConsumer()

    {

        // In this method you can check the username and password 

        // with your database or something

        // You could also encrypt the password for more security

        if (consumer != null)

        {

            if (consumer.userName == "Ahmed" && consumer.password == "1234")

                return true;

            else

                return false;

        }

        else

            return false;

        

    }



}



# region "SOAP Headers"



public class UserCredentials : System.Web.Services.Protocols.SoapHeader

{

    public string userName;

    public string password;

}



# endregion
SOAPHeaderService.asmx
<%@ WebService Language="C#" CodeBehind="~/App_Code/SOAPHeaderService.cs" Class="SOAPHeaderService" %>
 
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="microsoft.web.services3" type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </configSections>
  <system.web>
    <webServices>
      <soapExtensionImporterTypes>
        <add type="Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </soapExtensionImporterTypes>
      <soapServerProtocolFactory type="Microsoft.Web.Services3.WseProtocolFactory, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </webServices>
    <compilation>
      <assemblies>
        <add assembly="Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <customErrors mode="Off"></customErrors>
  </system.web>
</configuration>
 
 
Consumer
 
using System;

using System.Collections.Generic;

using System.Text;



namespace Consumer

{

    class Program

    {

        static void Main(string[] args)

        {

            SOAPHeaderService.SOAPHeaderService service = new SOAPHeaderService.SOAPHeaderService();

            SOAPHeaderService.UserCredentials user = new SOAPHeaderService.UserCredentials();



            user.userName = "Ahmed";

            user.password = "1234";



            service.UserCredentialsValue = user;



            Console.WriteLine(service.GetBalance());

        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值