Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8851075
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T13:03:37+00:00 2026-06-14T13:03:37+00:00

I am developing a WCF REST service where requests are authenticated using basic authentication

  • 0

I am developing a WCF REST service where requests are authenticated using basic authentication over SSL. However, before I send the authentication challenge I want to ensure that the request is valid using a pre-shared API key. I do not want the key value passed in the URL so is a custom HTTP header the best solution? Something like X-APIKey: keyvalue.

I am authenticating the user’s credentials in a HttpModule:

public void OnAuthenticateRequest(object source, EventArgs eventArgs)
    {
        HttpApplication app = (HttpApplication)source;

        if (!app.Request.IsSecureConnection)
        {
            app.Response.StatusCode = 403;
            app.Response.StatusDescription = "SSL Required";
            app.Response.End();
            return;
        }

        string authHeader = app.Request.Headers[AUTH_HEADER];
        if (authHeader == null)
        {
            app.Response.StatusCode = 401;
            app.Response.End();
            return;
        }

        ClientCredentials credentials = ClientCredentials.FromHeader(authHeader);
        if (credentials.Authenticate())
        {
            app.Context.User = new GenericPrincipal(new GenericIdentity(credentials.Id), null);
        }
        else
        {
            DenyAccess(app);
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T13:03:39+00:00Added an answer on June 14, 2026 at 1:03 pm

    That’s a good alternative (passing it in a header). You can then use a custom message inspector to validate that the shared key is present in all requests for a specific endpoint, as shown in the code below.

    public class StackOverflow_13463251
    {
        const string SharedKeyHeaderName = "X-API-Key";
        const string SharedKey = "ThisIsMySharedKey";
        [ServiceContract]
        public interface ITest
        {
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            string Echo(string text);
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            int Add(int x, int y);
        }
        public class Service : ITest
        {
            public string Echo(string text)
            {
                return text;
            }
            public int Add(int x, int y)
            {
                return x + y;
            }
        }
        public class ValidateSharedKeyInspector : IEndpointBehavior, IDispatchMessageInspector
        {
            public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
            {
            }
    
            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
            }
    
            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
                endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
            }
    
            public void Validate(ServiceEndpoint endpoint)
            {
            }
    
            public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
            {
                HttpRequestMessageProperty httpReq = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                string apiKey = httpReq.Headers[SharedKeyHeaderName];
                if (!SharedKey.Equals(apiKey))
                {
                    throw new WebFaultException<string>("Missing api key", HttpStatusCode.Unauthorized);
                }
    
                return null;
            }
    
            public void BeforeSendReply(ref Message reply, object correlationState)
            {
            }
        }
        static void SendRequest(string uri, bool includeKey)
        {
            string responseBody = null;
            Console.WriteLine("Request to {0}, {1}", uri, includeKey ? "including shared key" : "without shared key");
    
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
            req.Method = "GET";
            if (includeKey)
            {
                req.Headers[SharedKeyHeaderName] = SharedKey;
            }
    
            HttpWebResponse resp;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException e)
            {
                resp = (HttpWebResponse)e.Response;
            }
    
            Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
            foreach (string headerName in resp.Headers.AllKeys)
            {
                Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
            }
    
            Console.WriteLine();
            Stream respStream = resp.GetResponseStream();
            responseBody = new StreamReader(respStream).ReadToEnd();
            Console.WriteLine(responseBody);
    
            Console.WriteLine();
            Console.WriteLine("  *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*  ");
            Console.WriteLine();
        }
        public static void Test()
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "");
            endpoint.Behaviors.Add(new WebHttpBehavior());
            endpoint.Behaviors.Add(new ValidateSharedKeyInspector());
            host.Open();
            Console.WriteLine("Host opened");
    
            SendRequest(baseAddress + "/Echo?text=Hello+world", false);
            SendRequest(baseAddress + "/Echo?text=Hello+world", true);
            SendRequest(baseAddress + "/Add?x=6&y=8", false);
            SendRequest(baseAddress + "/Add?x=6&y=8", true);
    
            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am developing the REST enabled WCF Service. I am using the following code
I am developing a WCF service, which uses SSL certificate for transport security. I
I am developing a WCF service on my local computer using Visual Studios built
I'm currently developing a WCF REST Web Service that will be running on Microsoft
I'm developing a program using Windows 7. There are WCF services (soap, rest) that
I've been developing a WCF web service using .NET 3.5 with IIS7 and it
We're in the process of developing a WCF REST web service which just receives
We are working on developing a REST based WCF service. I was wondering if
The background I'm developing a REST API for a C#.NET web application using WCF.
I'm developing a Rest web service with WCF. I have the following contract: namespace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.