Question

I'm trying to get in memory hosting working for integration testing our web api project, but have hit an issue with authentication when using it. I have recreated this on a basic Web Api project using the default Web Api template and the values controller it creates.

We are using Autofac so have included this in the test too. We are also using windows authentication for the web api, but for the purposes of the test this is not important.

The issue is that the "server" in the test always returns "Authorization has been denied for this request."

So what is the best way to authorize with the in memory server? I've commented out some code from another stackoverflow question but that also didn't seem to work.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebApiTesting.Controllers;

namespace WebApiTesting.Tests.Controllers
{
    [TestClass]
    public class ValuesControllerTest
    {
        private const string URL = "http://test.testing.com/";
        private const string Username = "user";
        private const string Password = "supersecret";

        [TestMethod]
        public void InMemoryHosting()
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(name: "DefaultApi",
                                       routeTemplate: "api/{controller}/{id}",
                                       defaults: new {id = RouteParameter.Optional});
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var server = new HttpServer(config);
            var builder = new ContainerBuilder();
            // Register API controllers using assembly scanning.
            builder.RegisterApiControllers(typeof(ValuesController).Assembly);
            var container = builder.Build();
            server.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            var client = new HttpClient(server);
            using (var request = CreateRequest("api/values", "application/json", HttpMethod.Get))
            {
                //Act
                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    // Assert
                    Assert.IsNotNull(response.Content);
                    Assert.AreEqual("application/json", response.Content.Headers.ContentType.MediaType);
                    var content = response.Content.ReadAsStringAsync().Result;
                    Assert.AreNotEqual("{\"Message\":\"Authorization has been denied for this request.\"}", content);
                }
            }
        }

        private HttpRequestMessage CreateRequest(string url, string mthv, HttpMethod method)
        {
            var request = new HttpRequestMessage { RequestUri = new Uri(URL + url) };
            /*byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Username, Password));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(toEncodeAsBytes));*/
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
            request.Method = method;
            return request;
        }
    }
}
Was it helpful?

Solution

Just to document what worked in the end, I added the following line to my CreateRequest Method

Thread.CurrentPrincipal = new ClientRolePrincipal(new HttpListenerBasicIdentity(Username, Password));

I'm not really sure if this is the best way to handle it, but it does work at least.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top