namespace Ocelot.UnitTests.Authorization { using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Authorization; using Ocelot.Authorization.Middleware; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder.Middleware; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Responses; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; public class AuthorizationMiddlewareTests { private readonly Mock _authService; private readonly Mock _authScopesService; private Mock _loggerFactory; private Mock _logger; private readonly AuthorizationMiddleware _middleware; private RequestDelegate _next; private HttpContext _httpContext; public AuthorizationMiddlewareTests() { _httpContext = new DefaultHttpContext(); _authService = new Mock(); _authScopesService = new Mock(); _loggerFactory = new Mock(); _logger = new Mock(); _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); _next = context => Task.CompletedTask; _middleware = new AuthorizationMiddleware(_next, _authService.Object, _authScopesService.Object, _loggerFactory.Object); } [Fact] public void should_call_authorization_service() { this.Given(x => x.GivenTheDownStreamRouteIs(new List(), new DownstreamRouteBuilder() .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().Build()) .WithIsAuthorized(true) .WithUpstreamHttpMethod(new List { "Get" }) .Build())) .And(x => x.GivenTheAuthServiceReturns(new OkResponse(true))) .When(x => x.WhenICallTheMiddleware()) .Then(x => x.ThenTheAuthServiceIsCalledCorrectly()) .BDDfy(); } private void WhenICallTheMiddleware() { _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); } private void GivenTheDownStreamRouteIs(List templatePlaceholderNameAndValues, DownstreamRoute downstreamRoute) { _httpContext.Items.UpsertTemplatePlaceholderNameAndValues(templatePlaceholderNameAndValues); _httpContext.Items.UpsertDownstreamRoute(downstreamRoute); } private void GivenTheAuthServiceReturns(Response expected) { _authService .Setup(x => x.Authorize( It.IsAny(), It.IsAny>(), It.IsAny>())) .Returns(expected); } private void ThenTheAuthServiceIsCalledCorrectly() { _authService .Verify(x => x.Authorize( It.IsAny(), It.IsAny>(), It.IsAny>()) , Times.Once); } } }