I have just started learning lumen micro framework and having trouble as my middleware doesn't seem to work. here's my code.
//defined middleware in route
$app->get('/hello/{name}', ['middleware' => 'shield','uses' => 'Sampcontroller#show']);
//registered middleware in app.php
$app->routeMiddleware([
'shield' => App\Http\Middleware\Agemiddleware::class,
]);
Here it is middleware code
public function handle($request, Closure $next){
if ($request->input('name') == "18") {
echo "hate yew";
}
return $next($request);
}
}
Fix you class name (just for convention). AgeMiddleware (rename the file and the class).
Go to the bootstrap/app.php and register your route middleware
$app->routeMiddleware([
'shield' => App\Http\Middleware\AgeMiddleware::class,
]);
Make sure you put this snippet above the return statement.
Hit /hello/18.
If this doesn't work, you probably have another route above this one getting /home/something get requests.
Related
I'm currently using Laravel Passport, and I can verify that there is current token saved by using localhost:8000/api/check that returns json below:
{"id":"1c080ff73c6592b8e35630ae36f45f5042c04d9a9ed26a7fafc3793c606484b619ed8792be65a658","user_id":1,"client_id":5,"name":"Personal Access Tokens","scopes":["administrator"],...}
But when I tried to use middleware scope for admin using localhost:8000/api/admin it returns an error
Illuminate\Contracts\Container\BindingResolutionException: Target class [scope] does not exist. in file
Here is the routes/api.php
Route::group(['middleware' => 'auth:api'], function(){
Route::get('check', 'TeamController#check');
Route::group(['middleware' => 'scope:administrator'], function() {
Route::get('admin', 'TeamController#index');
});
});
Here's the corresponding functions on TeamController.php
public function check(Request $request) {
return auth()->user()->token();
}
public function index(Request $request) {
return auth()->user()->token();
}
Somebody knows what I went wrong?
You most likely did not register the scope middleware.
"Passport includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given scope. To get started, add the following middleware to the $routeMiddleware property of your app/Http/Kernel.php file:"
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
Laravel 7.x Docs - Passport - Checking Scopes
I'm using "laravel/lumen-framework": "5.7.*"
I have two middlewares, first one AuthTokenAuthenticate that should be applied to all the routes, so its defined in bootstrap/app.php like
$app->middleware([
App\Http\Middleware\AuthTokenAuthenticate::class
]);
Another middleware is defined like
$app->routeMiddleware([
'auth.token' => Vendor\Utilities\Middleware\AuthToken::class
]);
and will only be applied to some specific routes.
I need auth.token to be executed first, then AuthTokenAuthenticate but I can't find the way to do it because Lumen executes $app->middleware routes first.
Laravel has $middlewarePriority which is exactly what I need, but how can I handle it in Lumen?
I don't think this is possible in Lumen in the way you want to. What I suggest is using the middleware alongside the router group middleware options.
Remove the global middleware registration
/bootstrap/app.php
$app->middleware([
//App\Http\Middleware\AuthTokenAuthenticate::class
]);
Add both middlewares to the route middleware
/bootstrap/app.php
$app->routeMiddleware([
'auth.token' => Vendor\Utilities\Middleware\AuthToken::class,
'auth.token.authenticate' => App\Http\Middleware\AuthTokenAuthenticate::class
]);
Create two route groups: one with just auth.token.authenticate and one group with both auth.token and auth.token.authenticate.
/routes/web/php
$router->get('/', ['middleware' => 'auth.token.authenticate', function () use ($router) {
// these routes will just have auth.token.authenticate applied
}]);
$router->get('/authenticate', ['middleware' => 'auth.token|auth.token.authenticate', function () use ($router) {
// these routes will have both auth.token and auth.token.authenticate applied, with auth.token being the first one
}]);
I think this is the cleanest way to get the desired effect.
As of now with Lumen v6 (and possibly earlier), you can specify the middleware as an array field when defining your route. In the routes file web.php, I have something like the following:
$router->get('/api/path/to/thing', [
'uses' => 'FooController#index',
'middleware' => ['etag', 'caching', 'bar']
]);
Note how the the middleware field is an array with three elements. When this route is called, the middleware etag will execute first, then caching, then bar, in that order. When you only have a single middleware class, you can either specify it as a plain string or an array with just one element. This can of course be extended to route groups so that you have an entire class of routes that all use this middleware in this order.
I have the following lines in my routes/api.php
Route::middleware('api')->get('/posts', function (Request $request) {
Route::resource('posts','ApiControllers\PostsApiController');
});
When I hit http://localhost:8000/api/posts it comes back blank, but when I move the above route to routes/web.php like so:
Route::group(['prefix' => 'api/v1'],function(){
Route::resource('posts','ApiControllers\PostsApiController');
});
it works.
As a reminder I have cleared the routes cache file with php artisan route:clear and my route list comes with php artisan route:list when my routes/web.php is empty and routes/api.php has the above route:
Domain
Method
URI
Name
Action
Middleware
GET|HEAD
api/posts
Closure
api
Note that with web routes part the list comes ok and works fine.
What am I doing wrong here?
Dont use the middleware api and see following route example for API routes
Example 1 (in your api.php)
Route::get('test',function(){
return response([1,2,3,4],200);
});
visit this route as
localhost/api/test
Example 2 (if you want api authentication, token based auth using laravel passport)
Route::get('user', function (Request $request) {
///// controller
})->middleware('auth:api');
You can make get request for this route but you need to pass the access token because auth:api middleware has been used.
Note: see /app/http/kernel.php
and you can find the
protected $routeMiddleware = [
//available route middlewares
]
There must not be such (api) kind of middle ware in this file (kernel.php) for routes unless you create one, that why you can not use middleware as api.
Here, How I am creating REST APIs (api.php)
//All routes goes outside of this route group which does not require authentication
Route::get('test',function(){
return response([1,2,3,4],200);
});
//following Which require authentication ................
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
Route::get('user-list',"Api\ApiController#getUserList");
Route::post('send-fax', [
'uses'=>'api\ApiController#sendFax',
'as'=>'send-fax'
]);
Route::post('user/change-password', [
'uses'=>'api\ApiController#changePassword',
'as'=>'user/change-password'
]);
});
I want only my payment checkout pages in https. I have a website in http://, I´m implement a payment checkout with Stripe credit card, but Stripe only works with https...
I want that all my website have http, except the /payment-date page and the payment-data-post page, to send the data to Stripe with secure protocol.
How I can have only those two pages on https?
The routes are:
Route::get('/payment-data',['as'=> 'payment_data','uses' => 'WebController#getPaymentData']);
Route::post('/post-payment-data', ['as' => 'post_payment_data', 'uses' => 'WebController#postPaymentData']);
I want only this routes in https
The framework is Laravel 5.3
I think a good practice would be to create a Middleware which you then can use on whatever routes you'd like.
Using your Terminal, navigate to your project’s root directory and issue the following artisan command (to create ForceHttpProtocol middleware):
php artisan make:middleware ForceHttpProtocol
Change the newly created /app/Http/Middleware/ForceHttpProtocol.php so it looks something like this (will work only on production):
<?php
namespace App\Http\Middleware;
use Closure;
class ForceHttpProtocol {
public function handle($request, Closure $next) {
if (!$request->secure() && env('APP_ENV') === 'pro') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Next step is to update /app/Http/Kernel.php by adding the 'App\Http\Middleware\ForceHttpProtocol' which will make Laravel aware of your custom middleware.
If you want to apply middleware only on specific routes, you just have to assign middleware to routes by adding 'App\Http\Middleware\ForceHttpProtocol' instruction to $routeMiddleware array.
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
...
'forceSSL' => App\Http\Middleware\ForceHttpProtocol::class,
];
Just use the newly created middleware as you’re used to:
Route::get('payment-date', ['middleware' => 'forceSSL', function()
{
// do stuff
}]);
That should be it!
You can specify if routes should be HTTP or HTTPS by passing ['http' => true] or ['https' => true] as options when declaring your routes, if you don't specify those options then it should just use the same protocol as you're currently accessing the page with.
Route::post('/form', ['uses' => 'FormController#postForm', 'https' => true]);
How to create login for different users like admin,users and managers to redirect to different dashboards .
I read about middleware in laravel documentation but didnt got how to do.
i referred following link
http://laravel.com/docs/5.1/middleware#registering-middleware
http://laravel.com/docs/5.1/authentication#protecting-routes
Please help me.
Thank you in advance
You need to create a middleware for your route.
Use php artisan make:middleware AdminMiddleware.
You will find in your middleware folder a new file with this name.
Put your logic in your middleware e.g
public function handle($request, Closure $next)
{
if(Auth::check())
{
return $next($request);
}
else
{
return view('auth.login')->withErrors('You are not logged in');
}
}
Once you have done your logic in your middleware, you can either call it in the route or make the middleware apply to all routes.
if you want to add it to all routes go to Kernal.php and add it to the $middleware array e.g
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\AdminMiddleware',
];
If you want to add it to specific routes only, add it to the $routeMiddleware variable and add the alis to the route. e.g.
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'admin' => 'App\Http\Middleware\AdminMiddleware',
];
You can then add it to a route, as a filter e.g.
Route::get('admin/profile', ['middleware' => 'admin', function()
{
}]);
Note::this answer is given by stackoverflow user #Chris Townsend
Ref::
Roles with laravel 5, how to allow only admin access to some root
There is no need to provide different login for different users - you can simple login user and then check his role.
Suggest using Zizaco/Confide (https://github.com/Zizaco/confide) for users auth and Zizaco/Entrust (https://github.com/Zizaco/entrust/) for roles.
UPDATE
as OP doesn't want to use external packages:
route would look like this (for instance):
Route::put('post/{id}', ['middleware' => 'role:admin', function ($id) {
//
}]);
and in the middleware something to check if the user has a role:
if (! $request->user()->hasRole($role)) {
// whatever
}
UPDATE #2
Here is tutorial (based on Laravel 5.0 but should work):
http://heera.it/laravel-5-0-acl-using-middleware
For Laravel 5.1 Multiple Auth
https://github.com/Kbwebs/MultiAuth
You can use multiAuth for multiple authentication types
https://github.com/ollieread/multiauth
For Laravel 5
https://github.com/sboo/multiauth
You can achieve multiple authentication in laravel by using this package
https://packagist.org/packages/sarav/laravel-multiauth
Here I have already answered this question How to use authentication for multiple tables in Laravel 5
Answered same question here multiple login authentication
Create Controller and Middleware for multiple useres.
I used this method in my own project it's working.
You can try this.