briba
briba

Reputation: 2987

Authorization Header in SOAP call

I imported a WSDL to my C# .NET project. After that I had to generate an access token and now I have to use this token via authorization header while calling the SOAP service. Is there any easy way to to this?

MemberAccountPortClient clientTransaction = new MemberAccountPortClient ("SERVICE");
SearchTransactionResponseType res = clientTransaction.searchTransaction (OBJECT_1, OBJECT_2);

How can I add the authorization header in this case?

Upvotes: 2

Views: 2374

Answers (1)

dana
dana

Reputation: 18105

You can create an IClientMessageInspector / IEndpointBehavior to set this value as follows: (yes this code is verbose, but that's the way WCF works ;)

using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

public class AuthorizationHeaderMessageInspector : IClientMessageInspector, IEndpointBehavior
{
    object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        HttpRequestMessageProperty prop;
        Object obj;
        if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj))
        {
            prop = (HttpRequestMessageProperty)obj; // throws a cast exception if invalid type
        }
        else
        {
            prop = new HttpRequestMessageProperty();
            request.Properties.Add(HttpRequestMessageProperty.Name, prop);
        }
        prop.Headers[HttpRequestHeader.Authorization] = "your authorization value here";

        return null;
    }

    void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState)
    {
    }

    void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(this);
    }

    void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }

    void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
    {
    }
}

Then, when you create your client add the message inspector as follows:

MemberAccountPortClient clientTransaction = new MemberAccountPortClient ("SERVICE");
clientTransaction.Endpoint.Behaviors.Add(new AuthorizationHeaderMessageInspector());
SearchTransactionResponseType res = clientTransaction.searchTransaction (OBJECT_1, OBJECT_2);

I believe that WCF has a way to apply the IEndpointBehavior using configuration as well, but I usually go straight code for these types of things.

Upvotes: 3

Related Questions