Missing argument 1 for Illuminate\\Support\\Manager::createDriver() - laravel

I had a look at every post related to this error in Laravel:
Missing argument 1 for Illuminate Support Manager - createDriver()
2th link
3th link
None of them solved my issue: I am using Laravel Lumen version 5.4 and Dingo API package.
I want to access to the Authenticated User in the incoming request:
$request->user(); //returns an instance of the authenticated user
However this will throw me an error saying:
Missing argument 1 for Illuminate\Support\Manager::createDriver(), called in /var/www/html/myApp/vendor/illuminate/support/Manager.php on line 88 and defined",
I know that in order to get the Authenticated User, you need to provide the Auth Middleware inside the routing:
$api->get('register/{accountId}', ['middleware' => 'auth', 'App\Http\Controllers\Api\V1\RegisterController#registerAction']);
But adding the Middleware Auth inside my route will actually not reach the Controller endpoint and throw the same error that you can see above.
I have the AuthServiceProvider registered in my bootstrap/app.php:
$app->register(App\Providers\AuthServiceProvider::class);
And this is the AuthServiceProvider class:
<?php
namespace App\Providers;
use App\Models\Account;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider {
/**
* Register any application services.
*
* #return void
*/
public function register() {
}
/**
* Boot the authentication services for the application.
*
* #return void
*/
public function boot() {
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return Account::where('api_token', $request->input('api_token'))->first();
}
});
}
}
This is what I have in config/auth.php:
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
I tried to debug the issue myself and I found out that this is where it is breaking in Laravel:
/**
* Create a new driver instance.
*
* #param string $driver
* #return mixed
*
* #throws \InvalidArgumentException
*/
protected function createDriver($driver)
{
// We'll check to see if a creator method exists for the given driver. If not we
// will check for a custom driver creator, which allows developers to create
// drivers using their own customized driver creator Closure to create it.
if (isset($this->customCreators[$driver])) {
return $this->callCustomCreator($driver);
} else {
$method = 'create'.Str::studly($driver).'Driver';
if (method_exists($this, $method)) {
return $this->$method();
}
}
throw new InvalidArgumentException("Driver [$driver] not supported.");
}
I can see in the stackTrace that it is passing a NULL driver inside createDriver() method which cause the error that I'm having. I wonder if it is not a simple configuration thing that I have to add inside my .env file.
I am starting with Laravel Lumen, it's a great tool for building API and I'm not blaming the tool itself (I took a lot of time reading the beautiful documentation), I'm pretty sure that I missed something very simple, if someone can guide me to this, I will be very pleased.

Are you using Laravel Scout (with Algolia search driver)?
I came across the errors you seen while running my database seeds. In the end, I realized my tired mind forgot to define the correct env variables in my .env file, as below:
SCOUT_DRIVER=algolia
ALGOLIA_APP_ID=yourAlgoliaAppId
ALGOLIA_SECRET=yourAlgoliaSecret
If you haven't published the scout config file, do so with the following command:
php artisan vendor:publish
--provider="Laravel\Scout\ScoutServiceProvider"
Make sure you have put 'Laravel\Scout\ScoutServiceProvider::class' in the providers array in 'config/app.php' before running the above command.
Once I published the config file (named config/scout.php by default), I used the env variables as below:
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Search Engine
|--------------------------------------------------------------------------
|
| This option controls the default search connection that gets used while
| using Laravel Scout. This connection is used when syncing all models
| to the search service. You should adjust this based on your needs.
|
| Supported: "algolia", "elasticsearch", "null"
|
*/
'driver' => env('SCOUT_DRIVER'),
/*
|--------------------------------------------------------------------------
| Index Prefix
|--------------------------------------------------------------------------
|
| Here you may specify a prefix that will be applied to all search index
| names used by Scout. This prefix may be useful if you have multiple
| "tenants" or applications sharing the same search infrastructure.
|
*/
'prefix' => env('SCOUT_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Queue Data Syncing
|--------------------------------------------------------------------------
|
| This option allows you to control if the operations that sync your data
| with your search engines are queued. When this is set to "true" then
| all automatic data syncing will get queued for better performance.
|
*/
'queue' => false,
/*
|--------------------------------------------------------------------------
| Algolia Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your Algolia settings. Algolia is a cloud hosted
| search engine which works great with Scout out of the box. Just plug
| in your application ID and admin API key to get started searching.
|
*/
'algolia' => [
'id' => env('ALGOLIA_APP_ID'),
'secret' => env('ALGOLIA_SECRET'),
],
];
Once I did all of the above, the errors went away. This answer might not directly address your exact issue, but it could perhaps give you thoughts or aid your troubleshooting process.

Related

Spatie\Permission\Exceptions\GuardDoesNotMatch. Use guard `web` instead of `sanctum`

I saw that some similar questions already exist in stack overflown, but i am still confused and unable to understand what is not working and how i should make it work. I am trying to use Spatie\Permissions in my database seeder, but i get the message: 'The given role or permission should use guard web instead of sanctum. I am using sanctum guard to manage authentication and since it is an API for Mobile App, i don't want to want to change it for web. How could i solve this current problem?
My seeder:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use App\Models\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$role = Role::create(['name' => 'Super Admin']);
$user = User::create([
'username' => 'Motorbits',
'email' => 'motorbits#motorbits.com',
'password' => bcrypt('123456')
]);
$user->assignRole($role);
}
}
my config/auth:
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'sanctum',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
You can try adding
protected $guard_name = 'sanctum';
in your User.php file, it worked for me

Laravel Redis Sentinel Session

I'm looking to use redis sentinel to store laravel sessions.
I have set up redis this way:
When I use Laravel's Cache::put and do a dd(Redis::connection('cache-connection')->keys('*')).
I do have the new values that I wanted to cache.
However when I try to insert a new session value like this:
Session::put('dddd', 'test');
I get nothing new when I do a
dd(Redis::connection('session-connection')->keys('*')).
Moreover I could notice that I have the new value when I do a
dd(Session::all());
What I could have forgotten in the configuration of the sessions, I put you the configuration file below.
Thank you in advance for any help that would allow me to progress.
Configuration of database.php :
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
'cache-connection' =>[
'tcp://127.0.0.1:26379?timeout=0.1',
'tcp://127.0.0.1:26379?timeout=0.1',
'tcp://127.0.0.1:26379?timeout=0.1',
],
'options' => [
'replication'=>'sentinel',
'service'=>'***',
'parameters' =>[
'password' =>env('REDIS_PASSWORD', null),
'database' =>0,
],
],
'session-connection' =>[
'tcp://127.0.0.1:26379?timeout=0.1',
'tcp://127.0.0.1:26379?timeout=0.1',
'tcp://127.0.0.1:26379?timeout=0.1',
],
'options' => [
'replication'=>'sentinel',
'service'=>'***',
'parameters' =>[
'password' =>env('REDIS_PASSWORD', null),
'database' =>1,
],
],
],
Configuration of sessions.php :
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'redis'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 525600),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => 'session-connection',
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc", "memcached", or "dynamodb" session drivers you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
*/
'store' => env('SESSION_STORE', null),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
];
In my .env ihave this :
CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_DB=0
I know this is answer is coming an year after the last activity but I was going through the same issue and figured out that's normal that redis is not returning anything about the session before the end of the request.
Session data are made persistent only after the whole middlewares pipiline.
see here: https://github.com/laravel/framework/blob/9.x/src/Illuminate/Session/Middleware/StartSession.php#L127
that's how it looks the default session middleware of laravel:
protected function handleStatefulRequest(Request $request, $session, Closure $next)
{
// If a session driver has been configured, we will need to start the session here
// so that the data is ready for an application. Note that the Laravel sessions
// do not make use of PHP "native" sessions in any way since they are crappy.
$request->setLaravelSession(
$this->startSession($request, $session)
);
$this->collectGarbage($session);
$response = $next($request);
$this->storeCurrentUrl($request, $session);
$this->addCookieToResponse($response, $session);
// Again, if the session has been configured we will need to close out the session
// so that the attributes may be persisted to some storage medium. We will also
// add the session identifier cookie to the application response headers now.
$this->saveSession($request);
return $response;
}
I hope this helps ;)

How does Auth works with subdomains?

I have two subdomains and one domain.
api.pulsespace.test
myshop.pulsespace.test
pulsespace.test
The problem is that after logging in, I have a controller that returns the user info using Auth::User(), but this is returning null every time.
And if I try to visit the '/login' route, it will just redirect me to '/home'. Which means that user is logged in but Auth facade is somehow not working.
I've also defined a logout route. but upon accessing the website will start endless redirects.
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
Some other information:
SESSION_DOMAIN=.pulsespace.test
kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
//\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Barryvdh\Cors\HandleCors::class,
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* #var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
session.php
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION', null),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc", "memcached", or "dynamodb" session drivers you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
*/
'store' => env('SESSION_STORE', null),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_') . '_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE', false),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| do not enable this as other CSRF protection services are in place.
|
| Supported: "lax", "strict"
|
*/
'same_site' => null,
];
Any help would be very much appreciated.
Are they in the same server or different laravel instances?
Which Laravel version you're using?
Also, try cookie as a session driver (that's what I run in multiserver setup).
You also have to define the routes into your subdomain. For example wildcards:
Route::group(array('domain' => '{name}.yourdomain.com'), function () {
// your routes here
}

Authentication issue in laravel 5.6 using Multi tenancy and Multiple Modular structure

Development in laravel 5.6
I have installed this packages for implementing Multi-tenancy and Multiple-Modular system in laravel 5.6 :
1. "artem-schander/l5-modular": "^1.4",
2. "hyn/multi-tenant": "5.2.*",
The modular structure is like this:
laravel-project/`
app/
└── Modules/
└── Organization/
├── Controllers/
│ └── OrganizationController.php
├── Models/
│ └── Organization.php
├── Views/
│ └── index.blade.php
├── routes
│ ├── api.php
│ └── web.php
└── helper.php
Now I have faced a issue to fetch Auth User details into the Controllers under Organization Module.
Using route under Organization module and Default laravel route (route/web.php) it is default web.php in laravel.
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', 'DashboardController#index'); //Return All Users
//Route::get('dashboard', 'DashboardController#generalDashboard'); //Return All Users
Route::get('dashboard/{period}', 'DashboardController#renderDashboard'); //Return All Users
/* Route for Organization*/
Route::get('organization','\App\Modules\Organization\Controllers\OrganizationController#index');
});
and route under Organization Module is like :
Route::group(['module' => 'Organization', 'middleware' => ['web','auth'], 'namespace' => 'App\Modules\Organization\Controllers'], function() {
Route::resource('organization', 'OrganizationController');
});
and OrganizationController under Organization Module
namespace App\Modules\Organization\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//use Illuminate\Support\Facades\Auth;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use App\Repositories\Organization\OrganizationRepositoryInterface;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
use Validator;
use Redirect;
use Session;
use App\Http\Requests\OrganizationStoreRequest ;
use App\Traits\Custom\CustomResponseTrait ;
class OrganizationController extends Controller
{
use CustomResponseTrait ;
private $organizationRepo ;
public function __construct(OrganizationRepositoryInterface $organizationRepository){
$this->organizationRepo = $organizationRepository ;
//$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
dd(Auth::user()) ;
$organizations = $this->organizationRepo->all();
return view('Organization::test.index')->with('organizations', $organizations);
}
dd(Auth::user()) ; it will return null ,
but dashboardControiller in running well under default Controller directory in Laravel structure.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Modules\Psession\Models\Psession;
use App\Modules\Product\Models\Product;
use App\Modules\Comment\Models\Comment;
use App\Modules\ProductState\Models\ProductState;
use App\Modules\Image\Models\Image;
use App\Modules\Copywriting\Models\ProductCopywritingsession;
use App\Modules\Ounass\Models\Channel;
use Cache;
class DashboardController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(Product $product)
{
$this->middleware('auth');
$this->product = $product;
}
What should I do?
i'm facing similar projet with multi-tenancy, modules and tow different package to manage permissions.
I think that's not "modularity" approach causing problem, but maybe your Auth::user() returns null because in the default guard user doesn't exists.
To prevent any sharing models between tenant, system, guards, modules and all you'll use in your project i found a solution (hope this helps).
First of all i crate two different model to manage authentication: the User model using tenancy connection and God model using system connection (administration side). Once you created migration and setup for your new model i split logics into config\auth.php
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'god' => [
'driver' => 'session',
'provider' => 'gods',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
]
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class
],
'gods' => [
'driver' => 'eloquent',
'model' => App\Models\God::class
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'gods' => [
'provider' => 'gods',
'table' => 'password_resets',
'expire' => 60,
],
],
So, split all Auth controllers and views in two different sub-folders and update your routes to switch between which type of user you want to authenticate...
So in our old User authentication controllers override only methods to show the correct views:
ForgotPasswordController.php
public function showLinkRequestForm()
{
return view('agency.auth.passwords.email');
}
LoginController
public function showLoginForm()
{
return view('agency.auth.login');
}
RegisterController
public function showRegistrationForm()
{
return view('agency.auth.register');
}
ResetPasswordController
public function __construct()
{
$this->middleware('guest');
}
Repeat the same thing for all the "God" or new model created Auth Controllers but also add this in every controller
// adding guard declared into config/auth.php
protected function guard()
{
return Auth::guard('god');
}
Now if you use Auth::user() or Auth::guard('god')->user() you'll probably fix your issue because is probably inherited from Tenancy and not Modularity.
Hope this helps! ...and sorry for my bad english :)
In web middleware sessions start so you need to also add 'web' middleware
Replace below line
Route::group(['middleware' => 'auth'], function () {
With
Route::group(['middleware' => ['web','auth']], function () {

BindException: Local Error Laravel Adldap2/Adldap2

I am totally new with laravel and more with AD authentication.
I've been following the tutorial of these and I encountered the following problem, which can not find solution when trying to launch the application.
I have set the ' auto_connect '=> true and this error appears any attempt to access any direction from my page.
If you can also explain to me how these two functions bind and bindAsAdministrator are based and what items they want to link, can be great:
BindException: Local Error Browser Image
It is worth mentioning that my table has a username field.
My config/adldap.php:
/*
|--------------------------------------------------------------------------
| Connections
|--------------------------------------------------------------------------
|
| This array stores the connections that are added to Adldap. You can add
| as many connections as you like.
|
| The key is the name of the connection you wish to use and the value is
| an array of configuration settings.
|
*/
'connections' => [
'default' => [
/*
|--------------------------------------------------------------------------
| Auto Connect
|--------------------------------------------------------------------------
|
| If auto connect is true, anytime Adldap is instantiated it will automatically
| connect to your AD server. If this is set to false, you must connect manually
| using: Adldap::connect().
|
*/
'auto_connect' => true,
/*
|--------------------------------------------------------------------------
| Connection
|--------------------------------------------------------------------------
|
| The connection class to use to run operations on.
|
| You can also set this option to `null` to use the default connection class.
|
| Custom connection classes must implement \Adldap\Contracts\Connections\ConnectionInterface
|
*/
'connection' => Adldap\Connections\Ldap::class,
/*
|--------------------------------------------------------------------------
| Schema
|--------------------------------------------------------------------------
|
| The schema class to use for retrieving attributes and generating models.
|
| You can also set this option to `null` to use the default schema class.
|
| Custom schema classes must implement \Adldap\Contracts\Schemas\SchemaInterface
|
*/
'schema' => Adldap\Schemas\ActiveDirectory::class,
/*
|--------------------------------------------------------------------------
| Connection Settings
|--------------------------------------------------------------------------
|
| This connection settings array is directly passed into the Adldap constructor.
|
| Feel free to add or remove settings you don't need.
|
*/
'connection_settings' => [
/*
|--------------------------------------------------------------------------
| Account Prefix
|--------------------------------------------------------------------------
|
| The account prefix option is the prefix of your user accounts in AD.
|
| For example, if you'd prefer your users to use only their username instead
| of specifying a domain ('ACME\jdoe'), enter your domain name.
|
*/
'account_prefix' => '',
/*
|--------------------------------------------------------------------------
| Account Suffix
|--------------------------------------------------------------------------
|
| The account suffix option is the suffix of your user accounts in AD.
|
| For example, if your domain DN is DC=corp,DC=acme,DC=org, then your
| account suffix would be #corp.acme.org. This is then appended to
| then end of your user accounts on authentication.
|
*/
'account_suffix' => '',
/*
|--------------------------------------------------------------------------
| Domain Controllers
|--------------------------------------------------------------------------
|
| The domain controllers option is an array of servers located on your
| network that serve Active Directory. You can insert as many servers or
| as little as you'd like depending on your forest (with the
| minimum of one of course).
|
| These can be IP addresses of your server(s), or the host name.
|
*/
'domain_controllers' => ['190.168.124.147'],
/*
|--------------------------------------------------------------------------
| Port
|--------------------------------------------------------------------------
|
| The port option is used for authenticating and binding to your AD server.
|
*/
'port' => 80,
/*
|--------------------------------------------------------------------------
| Timeout
|--------------------------------------------------------------------------
|
| The timeout option allows you to configure the amount of time in
| seconds that your application waits until a response
| is received from your LDAP server.
|
*/
'timeout' => 5,
/*
|--------------------------------------------------------------------------
| Base Distinguished Name
|--------------------------------------------------------------------------
|
| The base distinguished name is the base distinguished name you'd like
| to perform operations on. An example base DN would be DC=corp,DC=acme,DC=org.
|
| If one is not defined, then Adldap will try to find it automatically
| by querying your server. It's recommended to include it to
| limit queries executed per request.
|
*/
'base_dn' => '',
/*
|--------------------------------------------------------------------------
| Administrator Account Suffix
|--------------------------------------------------------------------------
|
| This option allows you to set a different account suffix for your
| configured administrator account upon binding.
|
| If left empty, your `account_suffix` option will be used.
|
*/
'admin_account_suffix' => '',
/*
|--------------------------------------------------------------------------
| Administrator Username & Password
|--------------------------------------------------------------------------
|
| When connecting to your AD server, a username and password is required
| to be able to query and run operations on your server(s). You can
| use any user account that has these permissions. This account
| does not need to be a domain administrator unless you
| require changing and resetting user passwords.
|
*/
'admin_username' => env('ADLDAP_ADMIN_USERNAME', 'foo\saaa'),
'admin_password' => env('ADLDAP_ADMIN_PASSWORD', 'kaa#taa'),
/*
|--------------------------------------------------------------------------
| Follow Referrals
|--------------------------------------------------------------------------
|
| The follow referrals option is a boolean to tell active directory
| to follow a referral to another server on your network if the
| server queried knows the information your asking for exists,
| but does not yet contain a copy of it locally.
|
| This option is defaulted to false.
|
*/
'follow_referrals' => false,
/*
|--------------------------------------------------------------------------
| SSL & TLS
|--------------------------------------------------------------------------
|
| If you need to be able to change user passwords on your server, then an
| SSL or TLS connection is required. All other operations are allowed
| on unsecured protocols. One of these options are definitely recommended
| if you have the ability to connect to your server securely.
|
*/
'use_ssl' => false,
'use_tls' => false,
My Auth\Guard.php line with problem:
public function bind($username, $password, $prefix = null, $suffix = null)
{
// We'll allow binding with a null username and password
// if their empty. This will allow us to anonymously
// bind to our servers if needed.
$username = $username ?: null;
$password = $password ?: null;
if ($username) {
// If the username isn't empty, we'll append the configured
// account prefix and suffix to bind to the LDAP server.
$prefix = is_null($prefix) ? $this->configuration->getAccountPrefix() : $prefix;
$suffix = is_null($suffix) ? $this->configuration->getAccountSuffix() : $suffix;
$username = $prefix.$username.$suffix;
}
// We'll mute any exceptions / warnings here. All we need to know
// is if binding failed and we'll throw our own exception.
if (!#$this->connection->bind($username, $password)) {
throw new BindException($this->connection->getLastError(), $this->connection->errNo());
}
}
My config\auth.php:
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'adldap',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
My User.php:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','username'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My AuthController.php:
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Adldap\Contracts\AdldapInterface;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/tickets';
/**
* #var Adldap
*/
protected $adldap;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct(AdldapInterface $adldap)
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
$this->adldap = $adldap;
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
if ($this->adldap->auth()->attempt($request->email, $request->password, TRUE )) {
return 'entro';
// $this->validateLogin($request);
// // If the class is using the ThrottlesLogins trait, we can automatically throttle
// // the login attempts for this application. We'll key this by the username and
// // the IP address of the client making these requests into this application.
// $throttles = $this->isUsingThrottlesLoginsTrait();
// if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
// $this->fireLockoutEvent($request);
// return $this->sendLockoutResponse($request);
// }
// $credentials = $this->getCredentials($request);
// if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
// return $this->handleUserWasAuthenticated($request, $throttles);
// }
// // If the login attempt was unsuccessful we will increment the number of attempts
// // to login and redirect the user back to the login form. Of course, when this
// // user surpasses their maximum number of attempts they will get locked out.
// if ($throttles && ! $lockedOut) {
// $this->incrementLoginAttempts($request);
// }
// return $this->sendFailedLoginResponse($request);
}
}
}
First sorry for my english. I found the solution and I'm sure there are colleagues who like me, are new to the world of laravel, Adldap2 / Adldap2 and Active Directory, so I share the answer :).
I start by explaining important message error Adldap2 / Adldap2:
Can not contact LDAP server: This occurs when the IP address that we offer to the library, which is supposedly our AD server is not reachable. It must be emphasized that if we provide any IP that can be accessed, whether or not an AD server, this will no longer display this error. In short, we can have a completely wrong IP and the library does not indicate this explicitly and / or display the error explained below.
BindException: Local Error: It is quite possible that many of you will encounter this error, unlike other errors offered by the library, it lacks explicit description. This error is a consequence of what explained in the previous error. It happens when we have given to the library, a reachable IP but there is no AD server or configured on it. In my particular case, my AD server was not set.

Resources