Jens
Jens

Reputation: 1

Lumen does not detect https behind a reverse proxy

I have a Lumen API behind a reverse proxy in a docker container that only responds on port 80. So the client requests a certain domain https://xyz.ab/api/endpoint and everything works fine.

But if you want to use Request->secure() to check if you are on http or https lumen returns false (= http) and generates wrong urls.

I tried to use URL::forceScheme("https"); to tell lumen to use https anyways but lumen still insists on http.

I do not want to install a certificate inside my container only to make lumen believe in https.

Is there a place where I can configure lumen globally to use https instead of http?

Thank you.

Upvotes: 0

Views: 1657

Answers (2)

Maomao Sun
Maomao Sun

Reputation: 11

Here's a detailed implementation for those who are not so familiar with Lumen.

  1. Create a middleware(TrustedProxiesMiddleware) under App\Http\Middleware.

     <?php
    
     namespace App\Http\Middleware;
    
     use Illuminate\Http\Request;
    
     class TrustedProxiesMiddleware
     {
    
         /**
          *  use 0.0.0.0/0 if you trust any proxy, otherwise replace it with your proxy ips
          * 
          * @var string[]
          */
         protected $trustedProxies = [
             '0.0.0.0/0'
         ];
    
         public function handle(Request $request, \Closure $next){
             Request::setTrustedProxies($this->trustedProxies);
             return $next($request);
         }
     }
    
  2. In bootstrap/app.php file, add this middleware:

     $app->middleware([
         //other middlewares........
         App\Http\Middleware\TrustedProxiesMiddleware::class
     ]);
    
  3. Make sure your proxy sends X-FORWARDED-PROTO header to backend servers

Upvotes: 1

Jens
Jens

Reputation: 1

Thank you, PtrTon. That was exactly the right answer. Lumen uses Illumintae\Http\Request which extends Symfony\Component\HttpFoundation which includes the setTrustedProxies method.

So what I basically had to do, was:

  1. Create a middleware that sets trusted proxies.
  2. Create a config file with my trusted proxies.
  3. Configure my Reverse Proxy to forward the correct headers, which are:

    • X_FORWARDED_PROTO=https
    • X_FORWARDED_HOST={HTTP_HOST}
    • X_FORWARDED_FOR{HTTP_CLIENT_IP}
    • X_FORWARDED_PORT={SERVER_PORT}

For ssl it is enough to add X_FORWARDED_PROTO=https or X_FORWARDED_PORT=443 because these are the values that the secure() method is looking for. As soon as you add them and tell lumen to trust the proxy secure() returns true.

Upvotes: 0

Related Questions