Laravel: how to generate https url - laravel

I'm using Laravel 5.4 and have a question.
Is it possible to generate an https URL of the specific URL? I have a URL, e.g: login, and want to open it in https, not HTTP.
how can I force Laravel to open url('login') in https mode?

There is helper function secure_url(). The secure_url function generates a fully qualified HTTPS URL to the given path for e.g
$url = secure_url('user/profile');

If you want only some links in https, you can try this (force a group of routes to https):
Route::group(['scheme' => 'https'], function () {
// Route::get(...)->name(...);
});
Similar to this question: How to force Laravel Project to use HTTPS for all routes?

Related

404 Not Found on sanctum/csrf-cookie path

So I've been building a projet based on laravel. I'm building on a SPA foundation with sanctum as my authorization package. It works perfectly. Then I deploy the project to the server and everytime I try to login there is a 404 error on /sanctum/csrf-cookie.
How could this happen? Is it because the SanctumServiceProvider not working.
The problem is when you define sanctum prefix, the route become something else like this:
you can check your routes with : php artisan route:list
as you can see the /sanctum/ is removed and when you check the route /sanctum/csrf-cookie it will not be and throws 404 error. So you have two options:
add this prefix: 'prefix' => 'api/v1/sanctum'
or
change GET call to api/csrf-cookie
You need to check if you're setting correct axios defaults for your /sanctum/csrf-cookie api call.
You can set it as follows
axios.defaults.withCredentials = true;
axios.defaults.baseURL = "http://localhost"; //Before sending get request
axios.get("/sanctum/csrf-cookie").then(async () => {
//Logic to handle login
});
If defaults are not set properly url becomes http::localhost::8080/sanctum/crf-cookie which is where frontend is serving but instead it has to be http::localhost/sanctum/csrf-cookie
Note: localhost example is just for explanation. For production server make sure your url is correct and api call is on backend.
I solved this issue by adding:
AllowOverride All
to the apache directory config
add in last line inside config/sanctum.php
'routes' => false,
Add in config/cors.php
'paths' => ['*']

I have problem when deploy my laravel on herkou (Mixed Content)

Hello … l am finish Building website using Laravel and jQuery and bootstrap it's working good in local but when I upload to Heroku the file jQuery and bootstrap not working … it's work in local using http but in Heroku its need https its not working but when write http substitute of https it's working good like local and display Not Secure .. now any body know how can i allow website using https in Heroku or How can selection this problem
You should closely read all of Heroku's guide to getting started with Laravel.
The section titled "Trusting the Load Balancer" will resolve your issues.
Because of this:
This means that requests received by a dyno will have the last router’s IP address in the REMOTE_ADDR environment variable, and the internal request will always be made using the HTTP protocol, even if the original request was made over HTTPS.
Laravel sees HTTP requests coming in to the application, so it serves HTTP URLs for your various routes and asset URLs. As far as it knows, you're browsing via HTTP. The fix is to trust Heroku's "forwarded for" headers in your app's App\Http\Middleware\TrustProxies middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
protected $proxies = '*';
protected $headers = Request:: HEADER_X_FORWARDED_AWS_ELB;
}
Had this issue myself awhile back, there are a few options and some are more heavy handed than others. If you want to gauruntee that everything is always https no exceptions first update your APP_URL to 'https://example.com' then in the boot method of your AppServiceProvider add Url::forceScheme('https');
The less heavy handed option is to find all of the places you use the asset() helper and change it to secure_asset instead. The asset helper should use your APP_URL to know the request is https but in my experience I couldn't rely on that so use secure_asset to make sure

How can fix error (Mixed Content) when i uploed my project to herkou [duplicate]

Hello … l am finish Building website using Laravel and jQuery and bootstrap it's working good in local but when I upload to Heroku the file jQuery and bootstrap not working … it's work in local using http but in Heroku its need https its not working but when write http substitute of https it's working good like local and display Not Secure .. now any body know how can i allow website using https in Heroku or How can selection this problem
You should closely read all of Heroku's guide to getting started with Laravel.
The section titled "Trusting the Load Balancer" will resolve your issues.
Because of this:
This means that requests received by a dyno will have the last router’s IP address in the REMOTE_ADDR environment variable, and the internal request will always be made using the HTTP protocol, even if the original request was made over HTTPS.
Laravel sees HTTP requests coming in to the application, so it serves HTTP URLs for your various routes and asset URLs. As far as it knows, you're browsing via HTTP. The fix is to trust Heroku's "forwarded for" headers in your app's App\Http\Middleware\TrustProxies middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
protected $proxies = '*';
protected $headers = Request:: HEADER_X_FORWARDED_AWS_ELB;
}
Had this issue myself awhile back, there are a few options and some are more heavy handed than others. If you want to gauruntee that everything is always https no exceptions first update your APP_URL to 'https://example.com' then in the boot method of your AppServiceProvider add Url::forceScheme('https');
The less heavy handed option is to find all of the places you use the asset() helper and change it to secure_asset instead. The asset helper should use your APP_URL to know the request is https but in my experience I couldn't rely on that so use secure_asset to make sure

How to fix Laravel request/routes/urls - it thinks url is http when it is really https

My server uses SSL and thus all my routes/urls use https. I recently discovered a bug in Laravel 5.7 which was exposed when trying to use Email Verification, which does not work on a server with https. I wont go into the specifics of that problem as I have another question for that. I want to keep this simple.
I have the following settings in my .env file:
APP_USE_HTTPS=true
APP_URL=https://www.example.com
APP_ENV=production
And I have the following in the boot() method of the AppServiceProvider
if (env('APP_USE_HTTPS')) {
Log::info('AppServiceProvider: forcing URLs to use https');
URL::forceScheme('https');
}
And it may be overkill but to try to resolve the issue I also put the following code at the top of my web.php routes file"
if (env('APP_USE_HTTPS')) {
Log::info('Routes: forcing URLs to use https');
URL::forceScheme('https');
}
Route::get('/', 'PublicController#getHome');
Route::get('home', 'PublicController#getHome');
Then in my PublicController.getHome() method I put this code:
public function getHome()
{
$currentPath= Request::fullUrl();
Log::info($currentPath);
return view('public.home');
}
Now I go to my browser and enter this in the address bar:
https://www.example.com
And I get this in my log file:
AppServiceProvider: forcing URLs to use https
Routes: forcing URLs to use https
http://www.example.com
So as you can see from the last log message the fact that laravel always uses http instead of https is beginning to create issues. Starting with signed routes. I am trying to use the built-in Email Verification but the signature is being generated using https route and the email sent to user does have https in the url for going back to the same server. However the validation for the route is using http (even though https was used) so it generates a different signature and thus all verifications links fail with a 403 error.
Is there anything I am missing? I can't seem to find code that shows me how Laravel knows to use https or http or is it just hard coded for http?
Thanks for any help you can give me.
*** Update to show problem with Shaielndra Gupta answer ****
After implementing the middleware below is the code I used but as you will see the core problem exists in ALL methods dealing with url. So for example:
$request->secure()
returns false even when https was used. Then by calling:
redirect()->secure($request->getRequestUri());
does no good because that will cause the route to loop back into this method again which still returns false for secure(), basically creating an infinite loop (or infinite too many redirects)
class ForceHttpsProtocol {
public function handle($request, Closure $next) {
Log::info('request uri: '.$request->fullUrl());
Log::info('secure: '.($request->secure() ? 'yes' : 'no'));
if (!$request->secure() && env('APP_USE_HTTPS')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
The log from the above code will produce the following when you make 1 attempt to go to any page even when using https://www.example.com
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
< over and over till page times out >
After much research I finally discovered what the issue is.
My live server is installed on an Amazon EC2 server which is behind a Load Balancer.
The load balancer is receiving the (https) request and handling all the SSL requirements and then forwarding the request to my website as http.
To fix this issue I had to install the fideloper/TrustedProxy package. This package allows my site to trust the proxy and get the valid headers for the request so it now knows the request was actually sent using https.
Laravel wrote an article which describes my condition exactly.
https://laravel-news.com/trusted-proxy
This is the package I installed:
https://github.com/fideloper/TrustedProxy
change in your config/session.php
'http_only' => true,
change it to
'http_only' => false,
or make a middlewere HttpsProtocol.php
namespace MyApp\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class HttpsProtocol {
public function handle($request, Closure $next)
{
if (!$request->secure() && App::environment() === 'production')
{
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Then, apply this middleware to every request adding setting the rule at Kernel.php file in protected $routeMiddleware array,
'https'=>App\Http\Middleware\HttpsProtocol::class
change This
APP_USE_HTTPS=true
APP_URL=https://www.example.com
to this
APP_URL=http://www.example.com
APP_USE_HTTPS=false
Because Laravel uses APP_URL to generate urls.

Yii2 https URLs do not work

I try to run my local copy of my yii2 site with https.
I use this in config to force http url to https
'on beforeRequest' => function ($event) {
if(!Yii::$app->request->isSecureConnection){
$url = Yii::$app->request->getAbsoluteUrl();
$url = str_replace('http:', 'https:', $url);
Yii::$app->getResponse()->redirect($url);
Yii::$app->end();
}
},
The only url I can reach is the home page i.e. a bare url such as
example.ext
Other URLs give
Not Found The requested URL /site/index was not found on this server.
When removing the 'onbeforerequest' in the config, I can reach every http URL.
Question: why https URLs become unreachable?
Eventually I made out that there was no url rewrite for pretty url in the virtualhost litening to 443 port.
Adding the recommended rewrite rule in it solved the problem.
#stfsngue: Thank you for comment
Do you see any particular reason for preferring .htacces to 'onbeforeRequest' to force https?

Resources