Skip to content

Instantly share code, notes, and snippets.

@satish860
Created October 11, 2012 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satish860/3872715 to your computer and use it in GitHub Desktop.
Save satish860/3872715 to your computer and use it in GitHub Desktop.
Basic authentication with HTTP and Webapi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebAPIKoans.MessageHandlers;
using NUnit.Framework;
using System.Net;
namespace WebAPIKoans.Test
{
[TestFixture]
public class BasicAuthenticationHandlerTest
{
[Test]
public void should_send_401_if_the_authorization_is_not_there()
{
FakeInnerHandler innerhandler = new FakeInnerHandler();
innerhandler.Message = new HttpResponseMessage(HttpStatusCode.OK);
HttpMessageInvoker client = new HttpMessageInvoker(new BasicAuthenticationHandler { InnerHandler = innerhandler });
HttpRequestMessage requestMessage=new HttpRequestMessage(HttpMethod.Get,"http://localhost/order");
HttpResponseMessage message = client.SendAsync(requestMessage,new CancellationToken(false)).Result;
Assert.AreEqual(message.StatusCode, HttpStatusCode.Unauthorized);
}
[Test]
public void Should_Authorize_if_the_header_is_found()
{
FakeInnerHandler innerhandler = new FakeInnerHandler();
innerhandler.Message = new HttpResponseMessage(HttpStatusCode.OK);
HttpMessageInvoker client = new HttpMessageInvoker(new BasicAuthenticationHandler { InnerHandler = innerhandler });
HttpRequestMessage requestMessage=new HttpRequestMessage(HttpMethod.Get,"http://localhost/order");
var usernamepwd = Convert.ToBase64String(Encoding.UTF8.GetBytes("satish:password"));
var authorization = new AuthenticationHeaderValue("Basic",usernamepwd);
requestMessage.Headers.Authorization = authorization;
HttpResponseMessage message = client.SendAsync(requestMessage, new CancellationToken(false)).Result;
Assert.AreEqual(message.StatusCode, HttpStatusCode.OK);
}
}
}
namespace WebAPIKoans.Test
{
public class FakeInnerHandler:DelegatingHandler
{
public HttpResponseMessage Message { get; set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (Message == null)
{
return base.SendAsync(request, cancellationToken);
}
return Task.Factory.StartNew(() => Message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment