diff --git a/src/JwtAuthentication.php b/src/JwtAuthentication.php index 382d52a..6ea8928 100644 --- a/src/JwtAuthentication.php +++ b/src/JwtAuthentication.php @@ -124,7 +124,8 @@ public function __construct(array $options = []) */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - $scheme = $request->getUri()->getScheme(); + $forwardedProto = $request->getHeaderLine('X-Forwarded-Proto'); + $scheme = '' !== $forwardedProto ? $forwardedProto : $request->getUri()->getScheme(); $host = $request->getUri()->getHost(); /* If rules say we should not authenticate call next and return. */ @@ -136,8 +137,9 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface if ("https" !== $scheme && true === $this->options["secure"]) { if (!in_array($host, $this->options["relaxed"])) { $message = sprintf( - "Insecure use of middleware over %s denied by configuration.", - strtoupper($scheme) + "Insecure use of middleware over %s for host %s denied by configuration.", + strtoupper($scheme), + $host ); throw new RuntimeException($message); } diff --git a/tests/JwtAuthenticationTest.php b/tests/JwtAuthenticationTest.php index 05a6b44..9e28d04 100644 --- a/tests/JwtAuthenticationTest.php +++ b/tests/JwtAuthenticationTest.php @@ -551,6 +551,31 @@ public function testShouldNotAllowInsecure() $response = $collection->dispatch($request, $default); } + public function testShouldAllowInsecureIfForwardedProtoIsSecure() + { + $request = (new ServerRequestFactory) + ->createServerRequest("GET", "http://example.com/api") + ->withHeader("Authorization", "Bearer " . self::$acmeToken) + ->withHeader("X-Forwarded-Proto", "https"); + + $default = function (ServerRequestInterface $request) { + $response = (new ResponseFactory)->createResponse(); + $response->getBody()->write("Success"); + return $response; + }; + + $collection = new MiddlewareCollection([ + new JwtAuthentication([ + "secret" => "supersecretkeyyoushouldnotcommittogithub", + ]) + ]); + + $response = $collection->dispatch($request, $default); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals("Success", $response->getBody()); + } + public function testShouldAllowInsecure() { $request = (new ServerRequestFactory)