Laravel API Routing Middleware - php

I am running Laravel 5.4 and have my API routes setup with an API middleware that verifies an authentication token sent in the headers.
However, I want to avoid, or prevent the api/Login (route that generates the auth token) from being subject to the middleware.
Currently, in my API middleware, before any logic happens I have:
if(strpos($request->getUri(), 'Login')):
return $next($request);
endif;
I would like to remove checking if the route is the Login route before proceeding with the middleware logic. Is there a native way in Laravel to accomplish the above?
Note: all API routes are protected via an API middleware group which I have created in the Http/Kernel, then added the in the RouteServiceProvider.

You could add an except property in your middleware
Route::group(['middleware' => ['api'], 'except' => 'Login'], function () {
// Your Routes
});

Related

Slim Authentication middleware for all routes except someone

I would like to have a Slim middleware to check authentication on all requests but some specific ones (for example login page).
I prepared the first AuthenticationMiddleware middleware to check all pages:
$app->add(new \App\Middleware\AuthenticationMiddleware($container));
Then I create another one AnonymousMiddleware that it is supposed to add a variable to set the exception to authentication checks:
$app->group('',function() use ($app){
$app->get('/','LogicController:index');
})->add(new AnonymousMiddleware($container));
The problem is that routes middleware (AnonymousMiddleware) is applied AFTER the general middleware (AuthenticationMiddleware);
I tried to use determineRouteBeforeAppMiddleware but it doesn't change the result.
I know I would set a route middleware for all authenticated routes but sounds a bit dangerous if I forget it, so, I would prefer to set which router are not under authentication then keep the check all other routes.
you need to chose different approach
you need to wrap all routes which should be "protected via Auth middleware" and exclude = not wrap routes which should not be handled by this middleware
you can add a group where all your routes will live and only login (and logout) route will be outside of this group ;)
something like
$app->group("/api/v1", function() {
// all your protected routes definitions here
})
->add(AuthenticationMiddleware::class)); // wrap by middleware
$app->post('/login', function(){});
$app->add(new MiddlewareForAllRoutes()); // middlewares for all routes

Laravel override group middleware

How to override group middleware? What i want to achieve is to add other throttle limit for register/login routes.
My current throttle is set in kernel.
'api' => [
'throttle:40,1',
'bindings',
],
I want to set new throttle limit for login/register routes.
This is how i did it.
Route::post('login', 'Api\UserController#login')->middleware('throttle:15,3')->name('user.login');
Route::post('register', 'Api\UserController#register')->middleware('throttle:15,3')->name('user.register');
When i run php artisan route:list it says that this middleware api,throttle:15,3 is applied to this route.
The problem is when i run login request, response header says
X-RateLimit-Limit 40
X-RateLimit-Remaining 38
So as far as i see my new middleware is not applied. But my throttle requests are counted twice. How can i apply different middleware for throttle on login/register routes and override the old one ?
Old topic, but its the first i found; time for an updated answer.
I've had this problem in the past as well. My solution back then was to add the middleware in the constructor of the controllers. I dislike it but it works.
I'm currently using Laravel 8 with a new project and found that the following solution works:
Set the default middleware in kernel.php
'api' => [
'throttle:40,1',
'bindings',
],
Remove the middleware throttle:40,1 from the specific route, and add the correct middleware throttle:15,3:
Route::post('login', 'Api\UserController#login')->withoutMiddleware('throttle:40,1')->middleware('throttle:15,3')->name('user.login');
If you do not remove the middleware, it will run the throttle middleware twice per request.
I also played around with $this->middleware( 'throttle:40,1' )->except( ['login'] ) in the constructor of Api\UserController, however that does not give the required result; it will just add the middleware for all but one method, it does not overwrite.
Had this same question and just did some research. It doesn't appear that there is a way to overwrite the middleware configuration.
I, too, see that my middleware has updated in route:list but when resolving the middleware, it always uses a merged set of rules and so that initial api rule will end up overriding anything that defines something else over that.
You have a couple of options:
Remove the throttle rule from the Kernel api middleware definition and then use a Route::group() to re-add that specific rule to the rest of the routes. Then, in the same file, you can create a new Route::group() which defines the custom throttle config.
Route::group(['middleware' => 'throttle:120,1'], function () {
...
});
Route::group(['middleware' => 'throttle:15,3'], function () {
...
});
Create a custom api-auth.php file which is wrapped in a custom middleware group that you define just like the default api middleware. (You'll need to add another call in your RouteServiceProvider to load it like this:
public function map() {
...
$this->mapCustomAuthRoutes();
}
protected function mapCustomAuthRoutes()
{
Route::middleware(['throttle:15,3', 'bindings'])
->namespace($this->namespace)
->as('api.')
->group(base_path('routes/api-auth.php'));
}

Laravel How to get web or auth middleware to work

Developing a Laravel packages and in the routes I have this routes
Route::middleware(['web'])->group(function () {
Route::get('/pckOne', 'Frutdev\LaravPck\Controllers\PckController#getIndex');
Route::get('/pckZone', 'Frutdev\LaravPck\Controllers\PckController#getZone');
Route::post('/pckZone', 'Frutdev\LaravPck\Controllers\PckController#postZone');
Route::get('/pckUsers', 'Frutdev\LaravPck\Controllers\PckController#getUsers');
Route::get('/pckUser', 'Frutdev\LaravPck\Controllers\PckController#getCurrentUser');
Route::get('/pckArea', 'Frutdev\LaravPck\Controllers\PckController#getArea');
Route::post('/pckArea', 'Frutdev\LaravPck\Controllers\PckController#postArea');
Route::get('/{Area}/pckZones', 'Frutdev\LaravPck\Controllers\PckController#getAreaZones');
Route::post('/{Area}/pckZone', 'Frutdev\LaravPck\Controllers\PckController#postAreaZone');
});
The routes are not being authenticated.
I tried with the web middleware but can still see/access the routes while not logged in.
I tried with the auth middleware but even after logging in with the default Laravel loggin in system(which wasn't altered) I can't access the routes. It says I'm unauthorized, even after logging in. Any idea?
GET /login whenever I try to go with the auth middleware to /pckOne returns a 302 Found status.
To have the auth middleware functional you need something like the following:
Auth::routes();
Route::group(['middleware' => ['auth']], function () {
// Home Controller After Logging In
Route::get('/', 'HomeController#index')->name('home');
});
This means it will check auth before running the GET route. If you're signed in then great it'll run, if not your middleware will throw the sufficient redirect back to the login page as an example.

how to access API routes with middleware auth:api in laravel 5.3?

I am able to access routes declared in the api.php(route) with middleware 'api'. But not able to do the same with the routes that has 'auth:api'.
I guess only authenticated users can access the latter route. But when i access it after logging in , it just redirects me to home. how to fix this or am i following wrong procedure ?
Route::get('/user', function () {
echo "Hello";
})->middleware('auth:api');
Route::get('/work',function(){
echo "Hello";
})->middleware('api');
Check Laravel passport, it provides a nice way to implement OAuth2 and once you install passport create password client and make a post request to Oauth/token and get personal access_token.
Once you have the access_token you can make request to middleware auth:api

How to prevent to access visited page after logout in laravel using middleware class?

I want to make prevent access to visited page after logout from the laravel project. Here I have used laravel middleware
Route::group(['middleware' => ['web']], function ()
{
Route::get('/logout',[
'uses'=>'UserController#getLogout',
'as'=>'logout'
]);
});
I have included the all the routes in above Route::group route
and used auth facade. I want to prevent to access visited page after logout and after accidentally pressing the back button from the browser.
Laravel Route middleware can be used to allow only authenticated users to access a given route. All you need to do is attach the middleware to a route definition:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
Check this Laravel Auth Documentation

Categories