Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Respect X-Forwarded-Proto header for relaxation #185

Open
wants to merge 3 commits into
base: 3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/JwtAuthentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -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);
}
Expand Down
25 changes: 25 additions & 0 deletions tests/JwtAuthenticationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down