How to set Laravel 5 Middleware auth? - laravel

I am using Larave 5 for my project. In my project i am using laravel default auth which use this command php artisan make:auth. And i set middleware in my route.php as shown
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
Route::get('/', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController#showRoles');
});
Now my question is if i user is logout and click on browser back button user login and user can access like add, edit, delete view after logout. So how can i handle this situation. Please help i think some code i miss out.

First of all, your Route::auth() does already has login and logout functions, if you run 'php artisan route:list' in your terminal you can see which routes are available etc..
Second of all you can create a group like shown below for your admin stuff:
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
// Admin Roles Routes...
Route::group(['prefix'=>'admin', 'middleware'=>'auth'], function() {
Route::get('roles', 'AdminController#showRoles');
});
});
I hope this works for you ;)
Btw, the Laravel docs tell you a lot..., so make sure you watch them first ;)

First thing is you don't need to apply web middleware as it already applied to your routes by RouteServiceProvider, see https://laravel.com/docs/5.2/middleware#registering-middleware
Secondly, when use Route:auth() it is a shortcut for:
$this->get('login', 'Auth\AuthController#showLoginForm');
$this->post('login', 'Auth\AuthController#login');
$this->get('logout', 'Auth\AuthController#logout');
$this->get('register', 'Auth\AuthController#showRegistrationForm');
$this->post('register', 'Auth\AuthController#register');
$this->get('password/reset/{token?}', 'Auth\PasswordController#showResetForm');
$this->post('password/email', 'Auth\PasswordController#sendResetLinkEmail');
$this->post('password/reset', 'Auth\PasswordController#reset');
So you don't need to define these routes:
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
Lastly, why you put login on your home page?
Route::get('/', 'Auth\AuthController#getLogin');
This example should be work:
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
return 'Hello! You are logged in.';
});
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController#showRoles');
});
Route::auth();
With the routes above when unauthenticated user trying to access your home page http://yoursite.com and http://yoursite.com/admin/roles, user will be redirected to http://yoursite.com/login since those pages are protected by auth middleware.

An addition to #Rick answer.
You can also manually set a middleware inside the __construct() function of your controller.
Example:
// SomeController.php
public function __construct()
{
$this->middleware('auth');
}
Documentation

Related

Laravel 6: disable all routes for guest except home and login

I need to disable all routes for guests in Laravel except '/' and 'login' pages.
Does that possible to implement it routes/web.php ?
Yes. In your routes/web.php file, make sure to define your protected routes under the auth middleware group.
routes/web.php
Route::get('/', function() {
// / route
});
Route::get('/login', function() {
// login page
});
Route::middleware(['auth'])->group(function () {
// define your routes here
// they'll be protected
});
Official documentation
Since Laravel 7.7 you can use excluded_middleware property eg:
Route::group([
'excluded_middleware' => ['auth'],
], function () {
Route::get('/', 'HomeController#index');
...
});

Laravel Route not defined for registercontroller

I'm new to Laravel and I inherited a project. I saw that there was a app/Http/Controller/Auth/RegisterController.php, but going to the websites /register gave me a 404 error. So I added this line to routes/web.php
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
And now I can go to the url /register and sign up a new user without any issues.
I went into resources/views/auth/login.blade.php and added the line
Don't have an account? Sign up
But this gave me an error Route [register.create] not defined. View(.. path to login.blade.php
What did I do wrong?
Answer
The reason why you it's returning a 404 is because when you manually register the registration routes and you do it before the Auth::routes which registers one with the same key that overwrites yours. Hence why it's working if you move them after the Auth::routes.
What you could do is disable the register routes from the Auth facade:
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
Auth::routes(['register' => false]);
If you plan on using Laravel's default registration system, you simply have to remove your manually registered routes and create the respective views and you can access the route with route('register');.
You can also check the other available routes generated by the Auth facade with php artisan route:list.
Note
Also, you do not need to group them in the web middleware when adding routes in routes/web.php because they are automatically in the middleware by the RouteServiceProvider.
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
I solved the problem. I made a guess changed this:
Route::group(['middleware' => ['web']], function () {
... other code ...
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
Auth::routes();
... other code ...
});
To this
Route::group(['middleware' => ['web']], function () {
... other code ...
Auth::routes();
... other code ...
});
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
And it worked. NOt sure if this is the right way to do it though

Logout doesn't work when grouping routes by guest middleware

Using the built-in auth scaffolding, logout does not work when I assign the middleware guest to my logout route via a group.
Example:
Route::group(['middleware' => 'guest'], function () {
// login routes
Route::get('login', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController#login');
Route::get('logout', 'Auth\LoginController#logout')->name('logout');
// password reset routes
Route::get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController#reset');
});
The logout simply does not work and throws no error.
I have removed the middleware from all controller __construct() methods.
Try to exclude it like this:
Route::group(['middleware' => 'guest'], function () {
// login routes
Route::get('login', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController#login');
});
Route::get('logout', 'Auth\LoginController#logout')->name('logout')->middleware(['web', 'guest']);

Protect routes with middleware Laravel

I have implemented middleware roles and permissions control in my app, but I cannot figure out why it only allows me to define one '/' route. The second one is still pointing to '/home' even though I override AuthController redirectTo variable.
My routes:
Route::group(['middleware' => 'role:user'], function()
{
Route::get('/', 'ScoresController#user');
});
Route::group(['middleware' => 'role:admin'], function()
{
Route::get('/', 'PagesController#home');
});
In any case after authentication user with user role redirecting to '/home'.
Like Simon says your second route will override the first one what you could do is load another controller wich redirects you to another page via redirect()
or write it as a route itself.
Could look like this:
Route::get('/', function(){
$user = Auth::user();
if($user->is('admin') {
return redirect('admin');
}else{
return redirect('user');
}
});
Route::get('admin', ['middleware' => 'role:admin', 'uses'=> 'PagesController#home']);
This is just one of many possibilities hope it helps you.

Redirect to Login if user not logged in Laravel

i am new to laravel,
i have code in my controller's __construct like
if(Auth::check())
{
return View::make('view_page');
}
return Redirect::route('login')->withInput()->with('errmessage', 'Please Login to access restricted area.');
its working fine, but what i wants is. its really annoying to put these coding in each and every controller, so i wish to put this Verify Auth and redirect to login page in one place, may be in router.php or filters.php.
I have read some posts in forum as well as in stackoverflow, and added code in filters.php like below but that's too not working.
Route::filter('auth', function() {
if (Auth::guest())
return Redirect::guest('login');
});
Please help me to resolve this issue.
Laravel 5.4
Use the built in auth middleware.
Route::group(['middleware' => ['auth']], function() {
// your routes
});
For a single route:
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
Laravel docs
Laravel 4 (original answer)
That's already built in to laravel. See the auth filter in filters.php. Just add the before filter to your routes. Preferably use a group and wrap that around your protected routes:
Route::group(array('before' => 'auth'), function(){
// your routes
Route::get('/', 'HomeController#index');
});
Or for a single route:
Route::get('/', array('before' => 'auth', 'uses' => 'HomeController#index'));
To change the redirect URL or send messages along, simply edit the filter in filters.php to your liking.
To avoid code repetition, You can use it in middleware. If you are using the Laravel build in Auth, You can directly use the auth middleware as given,
Route::group(['middleware' => ['auth']], function() {
// define your route, route groups here
});
or, for a single route,
Route::get('profile', function () {
})->middleware('auth');
If you are building your own, custom Authentication system. You should use the middleware which will check the user is authenticated or not. To create custom middleware, run php artisan make:middleware Middelware_Name_Here and register the newly created middleware.
It's absolutely correct what other people have replied.
This solution is for Laravel 5.4
But just in case, if you have more than one middleware applying to routes, make sure 'auth' middleware comes in the end and not at the start.
Like this:
Route::prefix('/admin')->group(function () {
Route::group(['middleware' => 'CheckUser', 'middleware' => 'auth'], function(){
});
});
Route::middleware(['auth'])->group(function () {
Route::get('dashboard','BackendController#dashboard')->name('dashboard');
});
This entry in the web.php route will take the user [who is not logged in] to the login page if (s)he tries to access a 'protected' URL, "dashboard" in this case.

Resources