Laravel 5.3, using api.example.com to example.com/api - api

How to route api.example.com to example.com/api so i can just
api.example.com/v1/users
than using
example.com/api/v1/users.
I'm using nginx, thank you.

Ensure these 2 steps are in place.
Check your nginx configuration /etc/nginx/conf.d/example.conf and include the domain in the server_name like so:
server_name example.com api.example.com;
Check that you have a route setup within the routes/api.php file. Using the sub-domain group is optional but be sure that you have the correct routes.
Example of using domain group:
Route::group(['domain' => 'api.example.com'], function () {
Route::get('/v1/users', ['as' => 'api.users.index', 'uses' => 'UserController#index']);
}
Example without use of domain group and allowing for both URL to point to the same Controller (be sure to define its own route names as per the 'as').
Route::get('/v1/users', ['as' => 'api.users.index', 'uses' => 'UserController#index']);
Route::get('/api/v1/users', ['as' => 'users.index', 'uses' => 'UserController#index']);
Update:
Refer to official Laravel 5.3 documentation regarding the use of sub-domain routes https://laravel.com/docs/5.3/routing#route-group-sub-domain-routing

Related

Getting 401 unauthorized for Laravel sanctum

I am using Laravel Sanctum with Vuejs SPA. Both reside on same top level domain
Laravel backend : app.demo.localhost
Vue SPA : app-spa.demo.localhost
Login and logout (endpoints) are working correctly when called from VueJS SPA using axios and XSRF-TOKEN is succesfully set, but when I call other api end points it gives me 401 unauthorized.
In axios this is being set
axios.defaults.withCredentials = true;
I have the below configurations
In Laravel .env
SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost
In Routes/Api.php
Route::middleware('auth:sanctum')->get('api/user', function (Request $request) {
return $request->user();
});
In cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
Could someone help me out please?
If you are using php artisan serve add the port number to SANCTUM_STATEFUL_DOMAINS. So if your port number is 8000:
SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost:8000
Your SANCTUM_STATEFUL_DOMAINS must match the url in your browser. The port number should not be on the SESSION_DOMAIN.
Following are the 8 steps that I follow while setting up Laravel sanctum check if you missed anything
Step1 composer require laravel/sanctum
Step2 php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider
Step3 php artisan migrate (you can ignore this if you're using spa)
Step4 uncomment this line from app/http/kernel.php \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
Step5 In config/cors.php update 'supports_credentials' => true,
Step6 In .env file update SESSION_DRIVER=cookie & add new line of SESSION_DOMAIN=localhost (even if your using any port like 8080 just mention localhost in session_domain)
Step7 In config/sanctum.php add your client domain along with port(if local) in stateful as follows, in my case for vue CLI it's usually localhost:8080 & for nuxt its localhost:3000 , code is as follows
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:8000,localhost:8080,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
Mostly if your stateful (step7) is not setup properly you will get 401 unauthorized or it will try to redirect you to the home page along with cors policy error
Step8 Do not forget to await until sanctum/csrf-cookie promise is resolved
async login() {
await axios.get("http://localhost:8000/sanctum/csrf-cookie");
await axios.post("http://localhost:8000/login", {
email: "kunal#gmail.com",
password: "password",
});
let response = await axios.get("http://localhost:8000/api/user");
console.log(response.data);
},
For anyone dealing with localhost:
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8080(port number you use)
I just encountered the same problem. I configured all the options according to the official documentation, but I couldn't get the authorization.
Then I use routes/web.php instead of routes/api.php, so I can use sanctum middleware very well.
Now the problem seems obvious,Axios withCredentials maybe need to place in the correct way.
const http = axios.create({
baseURL: API_URL,
withCredentials: true
})
maybe not work. So I add {withCredentials: true} like
http.get('/api/whoami', {withCredentials: true})
.then(res => {
console.log(res.data)
})
Then it works.
But the very strange thing is that it is normal now, no matter whether I clear the browser cache, cookies or Laravel's various caches, there is no previous situation
For me i just had to place the host with port number:
SANCTUM_STATEFUL_DOMAINS=127.0.0.1:5173
and it started working.
Maybe this helps someone.
My problema was.... (no read with attention)
If your SPA needs to authenticate with private / presence broadcast channels, you should place the Broadcast::routes method call within your routes/api.php file:
Hi i found a solution.
My SPA is Vue v3 working on 3000 port.
Also my backend is working on 80 port. (laravel 8.1)
Make Stateful Domains in config/sanctum.php like that
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost:3000',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
Adding only one and correct domain on their, worked for me magically. I wrote before there whole possible variant of ports, it made me crazy and cost a couple days and nights.
My issue was I setup the domain in the wrong place.
I thought was an array of domains, in config/sanctum.php, but not, needs to be placed within the string:
OK:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,myownlocaldomain.test,myownlocaldomain.test:8080', <-------- OK
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
BAD:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : '',
'myownlocaldomain.test', <----- BAD
'myownlocaldomain.test:8080', <---- BAD
))),
I hope I save days of work to someone else...

Puppetlabs-Apache: enable both 80 and 443 for virtualhost

I'm relatively new to puppet and currently working on 'puppetlabs-apache' module. I'm missing something while setting both ssl and non-ssl on a virtual-host.
Manifest applied:
include apache
include apache::mod::rewrite
#apache::vhost { 'site.mydomain.com':
# port => '80',
# docroot => '/var/www/site',
# rewrite_rule => '(.*) https://site.mydomain.com [R,L]',
#}
apache::vhost { 'site.mydomain.com':
port => '443',
ssl => true,
docroot => '/var/www/site',
docroot_owner => 'www-data',
docroot_group => 'www-data',
# rewrite_rule => '(.*) https://site.mydomain.com [R,L]',
}
The thing is I don't need the non-ssl (80 port), but all requests should redirect to 443.
If I comment out the first vhost definition of site.mydomain.com for port 80, it throws an error:
Error 400 on SERVER: Duplicate declaration: Apache::Vhost[site2.mydomain.com] is already declared in file..
Not sure what I'm missing here. What should I do to make this permanent redirect happen?
http://site2.mydomain.com/ => https://site2.mydomain.com/
To configure a virtual host to redirect unencrypted connections to SSL, declare them with separate apache::vhost defined types and redirect unencrypted requests to the virtual host with SSL enabled:
apache::vhost { 'site.mydomain.com:80':
servername => 'site.mydomain.com',
port => '80',
docroot => '/var/www/site',
rewrite_rule => '(.*) https://site.mydomain.com [R,L]',
redirect_status => 'permanent',
redirect_dest => 'https://site.mydomain.com'
}
apache::vhost { 'site.mydomain.com:443':
servername => 'site.mydomain.com',
port => '443',
ssl => true,
docroot => '/var/www/site',
docroot_owner => 'www-data',
docroot_group => 'www-data',
rewrite_rule => '(.*) https://site.mydomain.com [R,L]',
}
You also needed those additional redirect attributes for the non-ssl virtualhost resource. Since apache::vhost is a defined resource type with no namevar, you can circumvent the multiple resource declaration issue by using two unique and purely cosmetic resource titles.
Working out Matt's answer and error while running it made me come at following answer.
apache::vhost { 'site.mydomain.com:80' ... }
apache::vhost { 'site.mydomain.com:443' : ...}
Thanks,

Puppet apach::vhost ssl_cert, ssl_key are not being created

Im trying to puppetize a server, and in the .pp apache config file I have:
apache::vhost { "000-default-ssl":
servername => "$sitename",
serveraliases => ["$sitename"],
serveradmin => 'webmaster#localhost',
port => '443',
docroot => "/path/to/docroot",
access_log_file => 'ssl-access.log',
error_log_file => 'ssl-error.log',
ssl => true,
ssl_cert => '/data/ssl/www/365_acdsee_com.crt',
ssl_key => '/data/ssl/www/365_acdsee_com.key',
#...morecode...
}
And when I run it, the file 000-default-ssl.conf is made and everything, but then when i look in /data/ssl/www/ it's empty. neither 365_acdsee_com.crt, or 365_acdsee_com.key are there.
So my question is: Is declaring the lines ssl_key and ssl_cert supposed to create the certificate and key, or do I have to have something else that generates them, and if not why isnt it making the files???
Is declaring the lines ssl_key and ssl_cert supposed to create the certificate and key ?
No. It will not generate cert and/or key. You have to generate these files manually or get from some cert provider.
Look at the source code of vhost.pp. These values are used to generate config file ${priority_real}${filename}.conf, from the _ssl.erb

Secured authentification for users Laravel 4

I'm working on a new Laravel 4 project and i would like to secure the authentication route over the SSL protocol and honestly i searched for 2 days with no luck and i have no idea how to do that.
That's my routes.php file:
Route::group(array('before' => 'guest'), function(){
/*==========================
| csrf PROTECTION
*///========================
Route::group(array('before' => 'csrf'), function(){
/*==========================
| Post Sign-in
*///========================
Route::post('/account/sign-in', array(
'as' => 'account-sign-in-post',
'uses' => 'AccountController#postSignIn'
));
});
/*==========================
| Get Sign-in
*///========================
Route::get('/account/sign-in', array(
'as' => 'account-sign-in',
'uses' => 'AccountController#getSignIn'
));
});
i would like to know if is that even possible using wamp, or it can be only done using a real host server, any help would be appreciated, and sorry for my bad English.
You can force routes to serve using https. For example:
Route::get('account/sign-in', array('https', function()
{
return 'Must be over HTTPS';
}));
ref: http://laravel.com/docs/routing

SSL for a website in Kohana

I have a website in Kohana 3.0.7 and I have purchased SSL certificate. I have marked the success page to which pay pal transaction details are returned with https. After the database is updated, I added following code -
$this->request->redirect('business/fnc_manage');
But this page is loaded with https and not loaded properly on Google Chrome.
If I try as following, it gives me 500 error -
header("Location:"+url::base()+"business/fnc_manage");
exit();
How can I get rid of this ? Does this mean that I'll have to ensure that all the resources loaded should be served over https ?
If yes, then I might have to change all the paths. How can I do it for HTML helpers ?
I have not tried it but I'd say changing the base_url in your bootstrap.php could help:
Kohana::init(array(
'base_url' => 'https://yoururlhere.com',
'index_file' => FALSE,
'charset' => 'utf-8',
'cache_dir' => APPPATH . 'cache',
'errors' => TRUE,
'profile' => Kohana::$environment !== Kohana::PRODUCTION,
'caching' => Kohana::$environment === Kohana::PRODUCTION,
));