I have been struggling with this from quiet a time now, what i am trying is to redirect all the url's hit by non-logged in users to login page and it gives me this error, which I am sure is because it is creating a loop on /login URL. authentication is checking for authorized user in login page also. however I wish the login page should be an exception when checking the auth. I may be doing something wrong which I am not able to get. here goes my code.
routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Auth\Access\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'acl' => \App\Http\Middleware\CheckPermission::class,
];
Authenticate class
class Authenticate
{
public function handle($request, Closure $next, $guard = null) {
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
AuthController class
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/dashboard';
protected $loginPath = '/login';
protected $redirectPath = '/dashboard';
public function __construct(){
$this->middleware('auth', ['except' =>'login']);
/* I have been trying these many things to fix this, all in loss.
// $this->middleware('acl'); // To all methods
// $this->middleware('acl', ['only' => ['create', 'update']]);
// $this->middleware('guest', ['only' => ['/login']]);
// echo "Message"; exit;
// $this->middleware('auth');
// $this->middleware('auth', ['only' => ['login']]);
// $this->middleware('auth', ['only' => ['/login']]);
// $this->middleware('auth', ['except' => 'login']);
// $this->middleware('guest');
// $this->middleware('guest', ['only' => ['logout' , 'login', '/login', '/']]);
}
Please help me, It going all above my head, seems some sort of rocket science to me. well btw I am new to laravel and may be doing some silly thing around, apologies for that. Thanks in Advance.
You need add route login outside Laravel group:
routes.php
Route::auth();
Route::group(['middleware' => 'auth'], function () {
// All route your need authenticated
});
Aditionally, you can see yours route list using:
php artisan route:list
Why you are doing all this just to redirect every non-logged in user to login form?
i think you can just do this
Routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
Route::group(['middleware' => 'auth'], function () {
// any route here will only be accessible for logged in users
});
and auth controller construct should be like this
AuthController
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
like #mkmnstr say
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
to fix that u should add
Auth::logout();
Here
...
} else {
Auth::logout(); // user must logout before redirect them
return redirect()->guest('login');
}
...
If your working with custom middleware you must follow it's all rules
in my case, I have to define a custom route class in the web middleware group.
In the world of copy-paste sometime we make mistakes.
Middleware :
public function handle($request, Closure $next)
{
if(!isset(session('user'))){
return redirect('login');
}
return $next($request);
}
}
My Mistake in Kernel.php
if custom middleware class present in web $middlewareGroups will check condition 2 times so it will give error as: redirected you too many times
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\webUser::class, //Remove
],
protected $routeMiddleware = [
'webUser'=> \App\Http\Middleware\webUser::class //Keepit
]
I had same problem after creating my own route service provider. The problem was that when I tried to login, in first time login page showed and after entering credentials I encountered "redirected too many times" and redirected to my admin dashboard and login route!
the solution was: adding middleware "web" into my routes:
Route::middleware('web')->group(base_path('Admin/routes.php'));
Related
I'm trying to create permissions and roles for users in a Laravel API Project. I'm using Passport and Spatie's Permission package. Using that I added a middleware:
Route
Route::middleware('auth:api')->group(function () {
/** Roles Route */
Route::get('roles',[RoleController::class, 'index'])->middleware('permission:role-list');
}
Handler.php:
public function render($request, Throwable $exception)
{
if ($exception instanceof UnauthorizedException) {
return response()->json(['User does not have the right roles.'],403);
}
return parent::render($request, $exception);
}
Controller:
function __construct()
{
$this->middleware('permission:role-list', ['only' => ['index']]);
$this->middleware('permission:role-create', ['only' => ['store']]);
$this->middleware('permission:role-edit', ['only' => ['update']]);
$this->middleware('permission:role-delete', ['only' => ['destroy']]);
}
public function index()
{
$roles = Role::all();
return response(['role' => $roles], 200);
}
I created an admin account and it was given all the existing permissions, but whenever I ask for the route, it shows me that error message:
User does not have the right roles.
I checked the database and the user had all the required permissions for that.
First of all add the package middlewares in the Kernel.php as described here.
protected $routeMiddleware = [
// ... other middleware
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
];
Depending on where you want to define the permissions to access a method either define them in the Controller or on the route. Adding them to both the route and Controller is only doing the same thing.
Changing something in the Handler.php should not be required.
Note that permissions can have different guards. For example it can be web or api.
After changing roles or permissions it sometimes helps to reset the cache. Resetting the cache can be done with php artisan permission:cache-reset command.
After logging in, my app always goes to the dashboard as intended.
But even after clicking other directories, it always goes to the dashboard.
As I find out, the middleware named RedirectIfAdmin always fires.
I am using hesto/multi-auth.
RedirectIfAdmin:
public function handle($request, Closure $next, $guard = 'admin')
{
if (Auth::guard($guard)->check()) {
return redirect('myapp/dashboard');
}
return $next($request);
}
On my admin route file:
Route::group(['prefix' => '/myapp', 'as'=>'myapp.'], function () {
Route::resources([
'user' => '\App\Http\Controllers\UserController'
]);
});
So if I go to myapp/user/ i am always redirected to myapp/dashboard.
I know that it was the code insde the RedirectIfAdmin that is firing when I go to myapp/user because if I change it to myapp/dashboard123 then it goes to that url everytime i browse myapp/user, myapp/user/create, myapp/user/123, myapp/user/123/edit, etc.
Any thoughts?
While calling your myapp/user/ try to call it with
project-url/admin/myapp/user
if you are calling with route then use like
admin.myapp.user
Step 1:
Inside your RouteServiceProvider.php
In that inside map function add this line:
$this->mapWebRoutes();
$this->mapAdminRoutes();
Step 2:
Inside RouteServiceProvider class add this function:
protected function mapAdminRoutes()
{
Route::group([
'middleware' => ['web', 'admin', 'auth:admin'],
'prefix' => 'admin',
'as' => 'admin.',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/admin.php');
});
}
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
Step 3:
Run below command in your project
php artisan optimize:clear
Check the __construct() on the user controller see if you referenced it there
I want to redirect user, if not authenticated, to my index page (which is the login page)
Can't seem to make it work and i really got confused with the routing.
HomeController
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return redirect()->guest('/');
}
}
Routing
// Index
Route::get('/', [
'as' => 'index',
'uses' => 'UserController#index'
]);
UserController
The routing as you see redirects to a User Controller at index function, which is the below :
*has __construct() so it uses the middleware 'auth'.
public function __construct()
{
$this->middleware('auth');
}
public function index(){
// If user is logged
if(Auth::check()) {
// If user has NOT submitted information form redirect there, otherwise to categories
if(!Auth::user()->submitted_information)
return redirect()->route('information');
else
return redirect()->route('categories');
}
else
return view('index', ['body_class' => 'template-home']);
}
Handler.php
And the unauthenticated function inside middleware of auth (Exceptions/Handler.php)
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('index');
}
The error i get right now is the below :
InvalidArgumentException in UrlGenerator.php line 304:
Route [index] not defined.
This error happens because of the line of
return redirect()->route('index'); in the above unauthenticated function.
What am i missing here? If you need any more information please feel free to ask.
EDIT : Until now, if i remove from UserController the __construct() method, and insert in web.php to all the routes what middleware to use, it works.
For example
Route::get('/categories', [
'as' => 'categories',
'uses' => 'UserController#showCategories'
])->middleware('auth');
But i am trying to find, without specifying there what middleware to use, to use it automatically.
Build your route like below code:
Route::group(['middleware' => ['auth']], function() {
// uses 'auth' middleware
Route::resource('blog','BlogController');
});
Route::get('/mypage', 'HomeController#mypage');
Open your middleware class named RedirectIfAuthenticated and then in handle fucntion
you write below code:
if (!Auth::check()) {
return redirect('/mypage'); // redirect to your specific page which is public for all
}
Hope it will work for you.
Your route should be like
// Index
Route::get('/','UserController#index')->name('index);
see here for more about routing.
Try
Route::get('/','UserController#index',['middleware'=>'auth'])->name('index);
I have these routes:
Auth::routes();
Route::get('/home', 'LibraryController#home');
Route::get('/', 'LibraryController#index');
Auth::routes() is generated by the command php artisan make::auth. But, i don't want the index page to be under auth middleware group, the third route in the above list.
Here is the controller methods. index() is for everyone and home() for authenticated users.
public function index()
{
return view('index');
}
public function home()
{
return view('home')->with('message','Logged in!');
}
the login users is redirected to home url:
protected $redirectTo = '/home';
But whenever i run the third route the login page appears. so, how can i remove that route from auth middleware group.
In your LibraryController before index where your controllers start you need to write
public function __construct()
{
$this->middleware('auth', ['except' => ['index']]);
}
Now every user will be able to go to index method without authentication
Documentation Reference https://laravel.com/docs/5.0/controllers#controller-middleware
Since Laravel 7.7 you can use excluded_middleware property eg:
Route::group([
'excluded_middleware' => ['auth'],
], function () {
Route::get('/home', 'LibraryController#home');
Route::get('/', 'LibraryController#index');
});
laravel authentication model
Is there any possible to make /register only you logged
How to make it with : (Auth::check()) ??
By default in construct of \app\Http\Controllers\Auth\AuthController.php we have middleware guest for all except logout:
public function __construct()
{
$this->middleware('guest', ['except' => [
'logout',
]
]);
}
Middleware guest link for:
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
And use handle method:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
It's mean that everybody who try access all Auth method except logout will be redirected to main page.
You should look at middleware if your are at laravel 5: https://laravel.com/docs/master/middleware
And filters for laravel 4: https://laravel.com/docs/4.2/routing