Laravel auth middleware returns route not defined - laravel

I'm new to laravel and I'm trying to secure some routes wherein only authenticated users can access it.
I've followed instructions on grouping my web routes on an auth middle ware, so I did my routes/web.php it like this...
Route::group(['middleware' => 'auth'], function () {
Route::get('/feed', [FeedController::class, 'feed']);
Route::get('/profile', [ProfileController::class, 'profile']);
});
Route::get('/', [LandingController::class, 'landing']);
and my App/Http/Middleware/Authenticate.php like this....
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('/');
}
}
but when I access these guarded routes unauthenticated, it gives me error saying
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [/] not defined.
Can someone point me on the right way here?

Related

Auth::user() is null in new route

i'm using laravel 6 and have 2 route in my app; index and dashboard.
My routes/web is:
Auth::routes();
Route::middleware(['auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController#index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard#dashboard')->name('dashboard');
});
i added dashboard route recently.
Auth::user() is null when i dump it in dashboard route but doesn't in index. What's the
Your Controller is instantiated before the middleware stack has ran; this is how Laravel can know what middleware you have set via the constructor. Because of this you will not have access to the authenticated user or sessions at this point. Ex:
public function __construct()
{
$this->user = Auth::user(); // will always be null
}
If you need to assign such a variable or access this type of information you would need to use a controller middleware which will run in the stack after the StartSession middleware:
public function __construct()
{
$this->middleware(function ($request, $next) {
// this is getting executed later after the other middleware has ran
$this->user = Auth::user();
return $next($request);
});
}
When the dashboard method is called, the middleware stack has already passed the Request all the way through to the end of the stack so all the middleware needed for Auth to be functioning and available has already ran at that point which is why you have access to Auth::user() there.
I think that this has something to do with the 'web' middleware. If you take a look into the Kernel.php (In app\Http) you will find the web middleware group.
This will show you that it actually calls a middleware called StartSession. Based on your route file (where web is not included as a middleware) I would think that you don't have a session in your Controller and there for no access to it.
I don't quite understand why this only happens in your /dashboard route, because the issue should also be in your /index route (unless you added the web middleware somewhere in your TodoController).
I think that this should do the trick:
Route::middleware(['web', 'auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController#index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard#dashboard')->name('dashboard');
});
If you fire php artisan make:auth command.
It's doesn't matter where you define because of it's only define auth route
Route::middleware(['auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController#index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard#dashboard')->name('dashboard');
});
Auth::routes();

Laravel Passport post route test on postman

I set up Laravel Passport and started to create a few Get routes to get some data, that worked fine.
Now I am trying to post to get on auth token, which currently does not work:
This is my route which I call (Get route works, Post route does not work):
Route::group(['middleware' => 'auth:api'], function ()
{;
Route::get('users', ['as' => 'users', 'uses' => 'ApiController#users']);
Route::post('login/{id}/{name}', ['as' => 'login', 'uses' => 'ApiController#login']);
});
The method in my ApiController looks currently like this:
public function login(Request $request, $id, $name)
{
if($request->isMethod('post'))
{
$id = $request->id;
$name = $request->name;
$inquiry = new Inquiry();
$inquiry->user_id = $id;
$inquiry->user_name = $name;
if($inquiry->save())
{
return redirect()->route('inquiry.index')->with('success', 'Success.');
}
else
{
return redirect()->route('inquiry.index')->with('error', 'An error accured.')->withInput();
}
}
else
{
dd("Use Post.");
}
}
I tried to call it with following options:
Edit
I somehow managed to get this work after many hours, but still dont understand something.
First I did following:
public function callback(Request $request)
{
dd($request->code) // this holds a token I need for the code parameter in the post
...
With that I could get the token for the code parameter, but I think there is a better way to do that.
And finally this is now how I get the access + refresh token:
But there has to be a better way to get the code token of the callback request ($request->code), instead of dumping it and copying it.
The problem is that you have your login route inside a route group with auth:api on it. This means the user needs to be authenticated to even be able to authenticate. Just remove the login route outside the group and you should be fine.
You should call the Passport::routes method within the boot method of your AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
/oauth/authorize route is already defined by the Passport::routes method. You do not need to manually define this route.

Removing a route from Auth::routes()

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');
});

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