laravel 5.7, haproxy and ssl - laravel

my project works locally (dev) like a charm, but in production, where I did set inside the .env file APP_URL as https://myurl, generated links are in http, so I get the mixed content problem. How to force ssl? App is behind Haproxy, which terminates SSL connection, inside a LXC container. Here's my TrustedProxies middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* #var array
*/
protected $proxies = [
'*'
];
/**
* The headers that should be used to detect proxies.
*
* #var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
any help?
Thanks

You can try this:
File: App/Providers/AppServiceProvider
public function boot()
{
\URL::forceSchema('https'); // Force HTTPS
}
Be sure on your .env files:
APP_URL = "https://"
Last step : File .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Related

HTTP 405 Method Not Allowed Lumen/Laravel

im trying to build an auth api for my react using lumen/laravel , each time i want to test it out with postman i get the following error HTTP 405 Method Not Allowed .
my routes :
$router->group(['prefix' => 'patient'], function () use ($router) {
$router->post('register',[PatientAuthController::class,'register'] );
$router->post('login', [PatientAuthController::class,'login'] );
});
CorsMiddlware :
class CorsMiddleWare
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
//Intercepts OPTIONS requests
if ($request->isMethod('OPTIONS')) {
$response = response('', 200);
} else {
// Pass the request to the next middleware
$response = $next($request);
}
// Adds headers to the response
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Expose-Headers', 'Location');
// Sends it
return $response;
}
PatientAuthController :
protected $patient;
protected $utilityService;
public function __construct()
{
$this->middleware("auth:patient",['except'=>['login','register']]);
$this->patient = new Patient;
$this->utilityService = new UtilityService;
}
public function register(PatientRegisterRequest $request)
{
$password_hash = $this->utilityService->hash_password($request->password);
$this->patient->createPatient($request,$password_hash);
$success_message = "registration completed successfully";
return $this->utilityService->is200Response($success_message);
}
/**
* Get a JWT via given credentials.
*
* #param Request $request
* #return Response
*/
public function login(LoginRequest $request)
{
$credentials = $request->only(['email', 'password']);
if (! $token = Auth::guard('patient')->attempt($credentials)) {
$responseMessage = "invalid username or password";
return $this->utilityService->is422Response($responseMessage);
}
return $this->respondWithToken($token);
}
.htaccess :
Options -MultiViews -Indexes
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
i have registred the middlware in app.php , but tho i still face this problem .

Laravel 5.8 VerifyCsrfToken Exception not working

I'm trying to exclude all requests on an endpoint which I call test.com/code so I do like this in the VerifyCsrfToken.php file.
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* #var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'code',
'code/*'
];
}
But it does not solve the issue, even after I try to run "php artisan route:clear && php artisan config:clear", Anyone knows why I can't exclude specific routes? (Laravel 5.8)
My route is something like this:
Route::get('code/testing', 'CodeController#testing');
I have try this and it didn't work either.
protected $except = [
'https://test.com/code/*',
];
Till now the only way I figure out is remove the line "\App\Http\Middleware\VerifyCsrfToken::class," from app/Http/Kernel.php to disable Csrf feature which is not a good solution.
Use / (slash) at the beggining :
protected $except = [
'/code/*'
];
You can try '/code/*'. It works for me with a slash / in the front of the url.

Google Cloud Kubernetes Laravel Get Visitor IP

I'm trying to get visitor IP on my Laravel application that uses Nginx on Google Cloud Kubernetes Engine, under load balancer.
I have set up TrustProxies.php like this:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* #var array
*/
protected $proxies = '*';
/**
* The headers that should be used to detect proxies.
*
* #var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
I have also tried
protected $proxies = '**';
And
protected $proxies = ['loadbalancer_ip_here'];
No matter what I have tried, it will always return load balancer ip.
Might this be caused by Nginx configuration? Help appreciated.
You have to set traffic policy in your nginx service
externalTrafficPolicy: "Local"
and also
healthCheckNodePort: "numeric port number for the service"
More details in Preserving the client source IP doc

routing in laravel with multiple htaccess

I want specific htaccess file for specific route.
For example, i want to allow all ips to home route of my site but prevent access specific ips to just payment route or specific routes.
Please help me with this problem.
you can use three solution:
laravel middleware
code Source
here:
namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\IpUtils;
class RedirectInvalidIPs
{
protected $ips = [
'65.202.143.122',
'148.185.163.203'
];
protected $ipRanges = [
'10.11.3.1',
];
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
foreach ($request->getClientIps() as $ip) {
if (! $this->isValidIp($ip) && ! $this->isValidIpRange($ip)) {
return redirect('/');
}
}
return $next($request);
}
protected function isValidIp($ip)
{
return in_array($ip, $this->ips);
}
protected function isValidIpRange($ip)
{
return IpUtils::checkIp($ip, $this->ipRanges);
}
}
.htaccess
code Source
here:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} /thisdirectoryandallcontents
RewriteCond %{REMOTE_ADDR} !=111.111.111.111
RewriteRule ^.*$ /maintenance.php [R=302,L]
Nginx allow and deny IP
CloudFlare
How do I control IP access to my site?
You should use middleware for access control, the .htaccess 'can' technically be used for this, but it is highly recommended not to.
Rough example of possible logic to filter based on ip, that can be put in the handle function of newly created middleware:
if (!in_array($request->ip, ['127.0.0.1', '::1'])) {
abort(403);
}
return $next($request);

Passing GET parameters to the default welcome controller

I've installed on my server new Codeigniter installation and I would like to be able to pass to the default controller (welcome) GET parameters.
For example:
http://www.myserver.com/1234
and I would like the default index function on the welcome controller will get '1234' as GET parameter, but I cant make it to work any idea?
here is my controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
// echo get parameter here = 1234
}
}
And my .htaccess code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Your controller should be like this
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index($number)
{
//$this->load->view('welcome_message');
echo get parameter here = 1234
}
}
In your config.php you can enable query strings:
$config['enable_query_strings'] = TRUE;
The access to the method using this url:
http://www.myserver.com/?id=1234
I think that should work.
On your route.php file
// Would leave as your default controller
$route['default_controller'] = 'welcome';
// But add get query route here
$route['number='] = 'welcome/index';
You need to have ? at the start of the query get and then after that any other url query use &.
And then on controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->helper('url');
echo anchor('?number=1234', 'Home', array('target' => '_blank'));
// http://www.example.com/index.php/?number=1234
echo '</br>';
echo $this->input->get('number');
$this->load->view('welcome_message');
}
}
When refresh page you should be able to see the anchor link which you can click on then will open new page and should display the numbers.
You also may come up with error disallowed uri
Then go to config and use ?&=
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-?&=';
You could alt use uri segments
<?php echo $this->uri->segment(1);?>
Use remap function
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
return call_user_func_array(array($this, $method), $params);
else
return call_user_func_array(array($this, 'index'), $params);
}
public function index($number)
{
//$this->load->view('welcome_message');
echo get parameter here = 1234
}
}

Resources