\Auth::user() is null in 5.3.6? - laravel

This is about Laravel 5.3.6
I am able to login successfully and I can check Auth User after login. I can show the exact location where Auth::guard() has current user object. Below are the details.
Go to Login Controller
Go to AuthenticatesUsers Trait
Go to sendLoginResponse method. User reaches here successfully because user is authenticated successfully.
here I can check $this->guard()->user() has current user value. But when control reaches to Role controller....I tried to access it like this dd(Auth::guard()); and value was null. I also added reference below in Role Controller.
use Illuminate\Support\Facades\Auth;
Below is my route for Role Controller.
Route::group(['middleware' => ['auth']], function () {
Route::get('/Roles',
array (
'uses' => 'Website\Role\RoleController#index',
'as' => 'Roles'
)
);
});
Did you face this kind of issue in Laravel 5.3.6?
Output of \Auth::guard() is below.
SessionGuard {#162 ▼
#name: "web"
#lastAttempted: null
#viaRemember: false
#session: Store {#165 ▶}
#cookie: CookieJar {#167 ▶}
#request: Request {#40 ▶}
#events: Dispatcher {#5 ▶}
#loggedOut: false
#tokenRetrievalAttempted: false
#user: null
#provider: EloquentUserProvider {#158 ▶}
}

Kernel.php file was like below
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
I changed it to like below.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
protected $middlewareGroups = [
'web' => [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];

Related

Laravel: Remove Request Throttling For Authenticated Users

I wish to disable request throttling for users that are authenticated through the API.
Kernel:
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' => [
'throttle:240,1'
],
];
Throttle here will limit the requests to 240 per minute regardless of whether or not a user is authenticated.
How would it be possible to do this so it only throttles unauthenticated users?
For the latest version of Laravel 8.x. We can use RateLimiter with the following steps:
In your app/Providers/RouteServiceProvider.php find below configureRateLimiting:
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
// Add this for no limit throttle
RateLimiter::for('none', function (Request $request) {
return Limit::none();
});
}
In your app/web.php add 'throttle:none':
Route::group([
'middleware' => ['auth', 'throttle:none'],
], function ($router) {
Route::post('test', 'TestController#test');
});
This step is optional, If you are using other middleware you can group them up in your app/Http/Kernel.php:
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' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'no_throttle' => [
'throttle:none',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Route::group([
'middleware' => ['auth', 'no_throttle'],
], function ($router) {
Route::post('test', 'TestController#test');
});
You could pack all auth routes to one group and set throttle to unlimited or in your controller class constructor you can disable ThrottleRequests middleware.
Please check this thread:
Disable rate limiter in Laravel?

Permission Middleware with Laravel 6.6 working on all routes

Hi I am working on laravel project , I have to check about user's permission when he trying to access one page , my problem is after I created Permission middle ware , and add it in the kernel.php , it checking about permissions for all route even I did not call it in any route .
I don't want to apply this middleware on all route , just some of it .
this is my permission middleware's code
namespace App\Http\Middleware;
use Closure;
use Session;
use App\Rules;
use Illuminate\Support\Facades\Route;
use URL;
class Permissions
{
public function handle($request, Closure $next) {
$rolename=Session::get('rule_name') ;
$route = $request->path();
$hasPermission = Rules::where('rule_name', 'superadmin')->where('allowed_pages', 'like', '%' . $route . '%') ->first();
if (empty($hasPermission)) {
echo 'Unauthorized.Go Back';
die();
}
}
}
}
and this is my route file
Route::resource('Login', 'LoginController')->name('index','Login');
Route::resource('Backup', 'BackupController')->name('index','Backup');
as you see I did not apply the middleware on these tow route , but the middleware is working with these tow routes
this is my kernel code
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,
'Permissions' => \App\Http\Middleware\Permissions::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
I want to run this middleware only by route like this
Route::group(['middleware' => 'permissions'], function () {
Route::resource('Backup', 'BackupController')->name('index','Backup');
}
thank you for advance
best regards
You added your middleware to the middelwareGroup web, wich applies the middleware to every request comming in.
You need to add your middleware to the routes middleware array: docs
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
...
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
// your own middlewares:
'Permissions' => \App\Http\Middleware\Permissions::class,
];
You can than apply the middleware to specific routes:
Route::resource('Login', 'LoginController')->middleware('Permissions')->name('index','Login');
you added inside web which is default middleware by laravel that's why it's applied in all route.
to register a middleware you need to add in protected $routeMiddleware = [ ] 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,
//custom middlewares:
'Permissions' => \App\Http\Middleware\Permissions::class,
];
then only
Route::group(['middleware' => 'permissions'], function () {
Route::resource('Backup', 'BackupController')->name('index','Backup');
}
it will work

Laravel Kernel load dynamic middleware array

want edit my Kernel.php file and disabled some Middleware in on place in aplication (I want my header response was shortly, here is my stack subject)
I have some idea but i don't know what is the next step:
class Kernel extends HttpKernel
{
public function __construct(Application $app, Router $router)
{
$url = \Illuminate\Http\Request::capture()->url();
if($url == 'http://autoservie.test/save'){
//HERE i want set protected $middlewareGroup and remove session
middleware from 'web'
}else{
// HERE set another protected $middlewareGroup
}
parent::__construct($app, $router);
}
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' => [
'throttle:60,1',
'bindings',
],
];
The question is, how set dynamic protected $middlewareGroups array in constructor? Or is there any other solution ?
You can do something like
$index = array_search(\Illuminate\Session\Middleware\StartSession::class, $middlewareGroups['web']);
unset($middlewareGroups['web'][$index]);

Laravel session cookie not encrypted when using AJAX

I'm about to create a single-sign-on interface for my app. The other app sends an AJAX POST request and I authenticate the user and return a response. A session cookie is beeing set, but it is not encrypted.
The relevant Code
$user = User::where('email', $email)->first();
if ($user) {
Auth::login($user);
return response("OK", 200);
}
My 'api' part in Kernel.php
'api' => [
'throttle:60,1',
'bindings',
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\App\Http\Middleware\EncryptCookies::class,
],
My route (no additional Middleware)
Route::post(
'/auth-request', [
'uses' => 'UserController#post_authenticateRequest',
'as' => 'authrequest'
]);
The EncryptCookies class in Kernel.php doesn't seem to have any effect in the AJAX post request - but only for the session part. When I manually add a cookie like
response("OK", 200)->cookie("mysession", Session::getId(), 60);
it is encrypted!
When I completely remove EncryptCookies in Kernel.php for both "api" and "web" the created session from the AJAX request is loaded correctly - but without encryption anymore.
How do I get the AJAX session cookie beeing encrypted? Do I need any other Middleware?
Thanks for your help.
After reading the comment from lagbox, I've tried several places for the EncryptCookies::class definition in my "api" part. I need to place it not only before StartSession but as the first element. And now it works!
My complete $middlewareGroups part in Kernel.php now looks like this:
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,
\App\Http\Middleware\App::class,
],
'api' => [
\App\Http\Middleware\EncryptCookies::class,
'throttle:60,1',
'bindings',
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
],
];
Hope this is helpfull.

Laravel 5.3 middleware execution order bug

I'm having a problem:
No matter what I do, the auth middleware is ALWAYS executed before other middlewares!
Here's what I tried:
Created a middleware named aa (so it comes before auth at least alphabetically).
I also put it before the auth one in Kernel.php
Then I created a nested route group:
Route::group(['prefix' => 'test', 'middleware' => 'aa'], function() {
Route::get('/', function() {
return 'test';
});
Route::group(['prefix' => 'test2', 'middleware' => 'auth:api'], function() {
Route::get('/', function() {
return 'test2';
});
});
});
If I go to /test/test2 the auth middleware gets executed before the aa one.
If I go to /test then I see the aa middleware is executed..
the middleware code is really easy:
public function handle($request, Closure $next)
{
dd('aa middleware!');
}
Here is Kernel.php as requested from #Rimon Khan
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'bindings',
],
];
protected $routeMiddleware = [
'aa' => \App\Http\Middleware\Aa::class,
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class
];
}
Edit: #prateekkathal you will never convert me to use spaces instead of tabs even if you force edit my post and change the indentation! lol
I got the answer. You should override the $middlewarePriority in your Kernel.php.
/**
* The priority-sorted list of middleware.
*
* Forces the listed middleware to always be in the given order.
*
* #var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];

Resources