Skip to content

Instantly share code, notes, and snippets.

@minajevs
Created December 5, 2019 07:42
Show Gist options
  • Save minajevs/824bc3c3c4661fc55005afd22002476d to your computer and use it in GitHub Desktop.
Save minajevs/824bc3c3c4661fc55005afd22002476d to your computer and use it in GitHub Desktop.
An example how to test a middleware or message handler, which uses `HttpContext.GetTokenAsync("access_token")`
//
// `GetTokenAsync` usage
//
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _httpContextAccessor.HttpContext.GetTokenAsync("access_token").Result);
return await base.SendAsync(request, cancellationToken);
}
//
// Mocking it in unit test
//
// Arrange
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://test.com");
var authProps = new AuthenticationProperties();
authProps.StoreTokens(new List<AuthenticationToken>
{
new AuthenticationToken{ Name = "access_token", Value = "test-jwt"}
});
var authenticationServiceMock = new Mock<IAuthenticationService>();
authenticationServiceMock.Setup(x => x.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
.ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), authProps, "Bearer")));
var serviceProviderMock = new Mock<IServiceProvider>();
serviceProviderMock
.Setup(s => s.GetService(typeof(IAuthenticationService)))
.Returns(authenticationServiceMock.Object);
var context = new DefaultHttpContext()
{
RequestServices = serviceProviderMock.Object
};
var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(x => x.HttpContext).Returns(context);
var handler = new AuthorizationHttpMessageHandler(contextAccessor.Object)
{
InnerHandler = new TestHandler((r, c) =>
{
// Assert 1
Assert.Equal("Bearer", r.Headers.Authorization.Scheme);
Assert.Equal("test-jwt", r.Headers.Authorization.Parameter);
return TestHandler.Return200();
})
};
var client = new HttpClient(handler);
// Act
var result = client.SendAsync(httpRequestMessage).Result;
// Assert 2
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment