diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs index 77f9775e..af7f5791 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs @@ -22,12 +22,12 @@ namespace Ocelot.Authentication.Middleware public async Task Invoke(DownstreamContext context) { - if (IsAuthenticatedRoute(context.DownstreamReRoute)) + if (context.HttpContext.Request.Method.ToUpper() != "OPTIONS" && IsAuthenticatedRoute(context.DownstreamReRoute)) { Logger.LogInformation($"{context.HttpContext.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated"); - + var result = await context.HttpContext.AuthenticateAsync(context.DownstreamReRoute.AuthenticationOptions.AuthenticationProviderKey); - + context.HttpContext.User = result.Principal; if (context.HttpContext.User.Identity.IsAuthenticated) @@ -41,7 +41,7 @@ namespace Ocelot.Authentication.Middleware $"Request for authenticated route {context.HttpContext.Request.Path} by {context.HttpContext.User.Identity.Name} was unauthenticated"); Logger.LogWarning($"Client has NOT been authenticated for {context.HttpContext.Request.Path} and pipeline error set. {error}"); - + SetPipelineError(context, error); } } diff --git a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs index d9ad9768..c173c82e 100644 --- a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs @@ -46,6 +46,20 @@ namespace Ocelot.UnitTests.Authentication .BDDfy(); } + [Fact] + public void should_call_next_middleware_if_route_is_using_options_method() + { + this.Given(x => GivenTheDownStreamRouteIs( + new DownstreamReRouteBuilder() + .WithUpstreamHttpMethod(new List { "Options" }) + .WithIsAuthenticated(true) + .Build())) + .And(x => GivenTheRequestIsUsingOptionsMethod()) + .When(x => WhenICallTheMiddleware()) + .Then(x => ThenTheUserIsAuthenticated()) + .BDDfy(); + } + private void WhenICallTheMiddleware() { _next = (context) => { @@ -68,9 +82,14 @@ namespace Ocelot.UnitTests.Authentication }; } + private void GivenTheRequestIsUsingOptionsMethod() + { + _downstreamContext.HttpContext.Request.Method = "OPTIONS"; + } + private void ThenTheUserIsAuthenticated() { - var content = _downstreamContext.HttpContext.Response.Body.AsString(); + var content = _downstreamContext.HttpContext.Response.Body.AsString(); content.ShouldBe("The user is authenticated"); } @@ -84,7 +103,7 @@ namespace Ocelot.UnitTests.Authentication { public static string AsString(this Stream stream) { - using(var reader = new StreamReader(stream)) + using (var reader = new StreamReader(stream)) { string text = reader.ReadToEnd(); return text;