Middleware - Call to undefined method Illuminate\Auth\RequestGuard::handle() - lumen

I am currently unable to protect my routes with the passport middleware. I am using lumen-passport, a package that makes Passport compatible with Lumen. When I attempt to hit the following route:
$app->get('/test', 'Game#test')->middleware('auth:api');
I get the following:
FatalThrowableError in AuthManager.php line 294:
Call to undefined method Illuminate\Auth\RequestGuard::handle()
in AuthManager.php line 294
at AuthManager->__call('handle', array(object(Request), object(Closure), 'api')) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Laravel\Lumen\Routing\{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in RoutesRequests.php line 780
at Application->sendThroughPipeline(array('auth:api'), object(Closure)) in RoutesRequests.php line 534
at Application->dispatch(null) in RoutesRequests.php line 475
at Application->run() in index.php line 28
My auth.php if it helps:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class
]
],
'passwords' => [
//
],
The route is correct as removing the middleware redirects to the appropriate controller as expected. Any help would be greatly appreciated.

For me the problem turned out to be my routes were in the wrong format. So to debug I commented out all existing routes and added the code (making sure APP_KEY=xxx is set in the .env file):
$app->group(['middleware' => 'auth:api'], function($app) {
$app->get('/user/info', function() {
$user = app('auth')->guard()->user();
return response()->json($user);
});
});
And the route /user/info worked without the error.
Then replaced my routes with the existing routes in the following format:
$app->group(['middleware' => 'auth:api'], function($app)
{
$app->get('/api/v1/users', [
'as' => 'listall', 'uses' => 'MyController#listModels'
]);
$app->get('/api/v1/users/{id}', [
'as' => 'list', 'uses' => 'MyController#listModel'
]);
$app->post('/api/v1/users', [
'as' => 'create', 'uses' => 'MyController#createModel'
]);
$app->delete('/api/v1/users/{id}', [
'as' => 'delete', 'uses' => 'MyController#deleteModel'
]);
$app->put('/api/v1/users/{id}', [
'as' => 'update', 'uses' => 'MyController#updateModel'
]);
});
And the error was no longer thrown.

In your bootstrap/app.php file, you need to make sure to uncomment the auth middleware setup.
https://github.com/laravel/lumen/blob/v5.4.0/bootstrap/app.php#L66-L68:
// $app->routeMiddleware([
// 'auth' => App\Http\Middleware\Authenticate::class,
// ]);
If the auth middleware is not registered, I believe Lumen will attempt to resolve auth out of the container (resolving to the AuthManager) and will attempt to treat it as middleware (calling handle on it, which doesn't exist).

I donĀ“t know if you resolve your problem, but i had the same one and I resolved it adding the middleware 'auth:api' inside the constructor of the Controller, in my case UserController:
public function __construct(){
$this->middleware('auth:api');
}

you have to add this code in Authenticate.php
public function __construct(Guard $auth)
{
$this->auth = $auth;
}

All you have to do is in you app.php located in bootstrap folder.
There you should define passport middleware.
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class
]);
When it's done you have to set your protected urls to client_credentials middleware.
When it's done try to make request with token to your protected route and for example return Auth::id().
You will receive user id for this token.
Regards

Related

OPTION verb is not working for a list of all records in Yii 2 app

I have created a blank Yii 2 project that have created a REST UserController for already existing User model:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
I have modified the model to have all fields safe:
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
[['username', 'email'], 'required'],
[['username', 'email'], 'unique'],
['email', 'email'],
[['password_hash', 'password_reset_token', 'verification_token', 'auth_key', 'status,created_at', 'updated_at', 'password'], 'safe'],
];
}
I have configured URL rules to have both pluralized and non-pluralized paths:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false,
'except' => ['index'],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'patterns' => [
'GET,HEAD,OPTIONS' => 'index',
],
],
],
I have enabled JSON input, if that matters:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
All the verbs are processed correctly except for OPTIONS /users:
When I execute OPTIONS /user/20 then I am getting:
200 OK
Empty content
List of allowed methods
But, when I execute OPTIONS users then I am getting 405 Method not Allowed.
What can be wrong or what am I missing?
You are getting 405 Method Not Allowed not because of routing but because of yii\filters\VerbFilter.
The yii\rest\Controller uses verbs() method to set up VerbFilter.
The yii\rest\ActiveController overrides verbs() method and sets VerbFilter to only allow GET and HEAD requests for index action.
It uses options action for OPTIONS method.
If you really want to use index action for OPTIONS method. You have to override verbs() method yourself and add OPTIONS as allowed method for that action. For example like this:
protected function verbs()
{
$verbs = parent::verbs();
$verbs['index'][] = 'OPTIONS';
return $verbs;
}
Or if you want to use options action you have to modify patterns settings as suggested by #Bizley in comments.

Aura Router AJAX Route Failure - Route Not Found

To preface this question, I'm converting a demo application to utilize RESTful, SEO-friendly URLs; EVERY route with the exception of one of two routes used for AJAX requests works when being used in the application on the web, and ALL the routes have been completely tested using Postman - using a vanilla Nginx configuration.
That being said, here is the offending route definition(s) - the login being the defined route that's failing:
$routing_map->post('login.read', '/services/authentication/login', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'login',
]
]
])->accepts([
'application/json',
]);
$routing_map->get('logout.read', '/services/authentication/logout', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'logout',
]
]
])->accepts([
'application/json',
]);
With Postman & xdebug tracing I think I'm seeing that it's (obviously) failing what I believe to be a REGEX check in the Path rule, but I can't quite make it out. It's frustrating to say the least. I looked everywhere I could using web searches before posting here - the Google group for Auraphp doesn't seem to get much traffic these days. It's probable I've done something incorrectly, so I figured it was time to ask the collective user community for some direction. Any and all constructive criticism is greatly welcomed and appreciated.
Thanx in advance, and apologies for wasting anyone's bandwidth on this question...
Let me make something clear. Aura.Router doesn't do the dispatching. It only matches the route. It doesn't handle how your routes are handled.
See the full working example ( In that example the handler is assumed as callable )
$callable = $route->handler;
$response = $callable($request);
In your case if you matched the request ( See matching request )
$matcher = $routerContainer->getMatcher();
$route = $matcher->match($request);
you will get the route, now you need to write appropriate ways how to handle the values from the $route->handler.
This is what I did after var_dump the $route->handler for the /signin route .
array (size=1)
'params' =>
array (size=1)
'values' =>
array (size=2)
'controller' => string '\Infraweb\LoginUI' (length=17)
'action' => string 'read' (length=4)
Full code tried below. As I mentioned before I don't know your route handling logic. So it is up to you to write things properly.
<?php
require __DIR__ . '/vendor/autoload.php';
use Aura\Router\RouterContainer;
$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$map->get('application.signin.read', '/signin', [
'params' => [
'values' => [
'controller' => '\Infraweb\LoginUI',
'action' => 'read',
]
]
]);
$map->post('login.read', '/services/authentication/login', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'login',
]
]
])->accepts([
'application/json',
]);
$matcher = $routerContainer->getMatcher();
// .. and try to match the request to a route.
$route = $matcher->match($request);
if (! $route) {
echo "No route found for the request.";
exit;
}
echo '<pre>';
var_dump($route->handler);
exit;
For the record, this is the composer.json
{
"require": {
"aura/router": "^3.1",
"zendframework/zend-diactoros": "^2.1"
}
}
and running via
php -S localhost:8000 index.php
and browsing http://localhost:8000/signin

URL-Manager will not route

I cloned our repositorie and created excatly the same URL-rules like at my own project. Now, i will get error like this after having logged in:
Firefox:
Fehler: Umleitungsfehler
The website called is rerouting request,which never will come to an end.
This problem sometimes occures, if cookies are deactivated
Chrome:
ERR_TOO_MANY_REDIRECTS
I definetly accepted using cookies at both browser!!
Debugging shows me,that I have dozen of 302-Requests,so Yii breaks down!
I use Windows, not LINUX, so I don't care about any permissions.
Here are the rules:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => true,
'enableStrictParsing' => true,
'rules' => [
'/' => 'site/login',
'home' => 'site/index',
'logout' => 'site/logout',
'contact' => 'site/contact',
'signup' => 'site/signup',
'reset' => 'site/request-password-reset',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<action:(contact|captcha)>' => 'site/<action>'
],
Here is frontend configuration:
<?php
$config = [
// LZA 17-07-30
'sourceLanguage' => 'de-DE',
'language' => 'de-DE',
// LZA 17-07-30 siehe Funktionen in http://demos.krajee.com/grid#module
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '4lD2RxDNkC4ckpwxTmkDzOLIvk0JMs3F',
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// LZA 17-07-30 CRUD
'generators' => [// customized CRUD generator
'crud' => [
// 'class' => 'app\myCrud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'class' => '\common\wsl_dev\wsl_crud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'templates' => [
'myCrud' => '/#common/wsl_dev/wsl_crud/crud/default', //LZA 17-07-20 Templatename und Templatepfad
]
]
],
// LZA 17-07-30 CRUD
];
}
return $config;
If I deacitvate URLManger,setting
'enablePrettyUrl' => false,
everything works fine.
If I put in manually Url like this:
http://localhost/yii2_perswitch/frontend/web/yiic.php/home
everything works fine,too
Any ideas,how to fix this?
I deleted all my cookies,without any effects!
Solution 1:
Enable debug mode from web/index.php (uncomment these two lines):
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
and you can see exactly what causes the problem.
Redirected too many times error was because the 777 permissions for
runtime and assets folder were not set.
Solution 2:
I think that the problem is related with the path or domain of the cookie. I believe that this info could be useful.
https://github.com/samdark/yii2-cookbook/blob/master/book/cookies.md

Yii2 mongodb error Object configuration must be an array containing a "class" element

When I try to login OR Signup it does not work. If I try to login with wrong credential it works. But if I use right credential it gives error:
Object configuration must be an array containing a "class" element.
Error on line:
static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
and related line
$models = $this->createModels($rows);
My config is as below
main.php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
];
main-local.php
return [
'components' => [
'mongodb' => [
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://mts:123456#localhost:27017/mangodb',
],
'user' => [
'identityClass' => 'common\models\User', // This is your class with IdentityInterface
'enableAutoLogin' => true,
],
],
];
Make sure the ActiveRecord object you are using (the one in static::findOne(...)) is an instance of yii\mongodb\ActiveRecord and not yii\db\ActiveRecord because the latter uses standard db component I assume you have not got configured.

Yii2 restful not working

By using this link I tried to have a restful app, but it's not working and always returned this:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please > > check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.4 (Win32) OpenSSL/1.0.1e PHP/5.5.1
I call it like this: localhost/restful/web/users
Edit:
This kind of call is not working either: localhost/restful/web/?r=users
It returned this:
Not Found (#404)
Page not found.
The above error occurred while the Web server was processing your request.
Please contact us if you think this is a server error. Thank you.
Have the same error (stil getting 404 Not found on each request) have solve it adding .htaccess to (my yii path)/web folder (the same where you have index.php):
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
This is because when you create an clean instance of Yii2 you don't have the .htaccess file (in my opinion probably the security reason).
for me the: (enabling curl and using it in my controller) installed via composer
composer require --prefer-dist linslin/yii2-curl "*"
use in controller
<?php
namespace app\controllers;
use yii\rest\ActiveController;
use linslin\yii2\curl;//this was added
class UserController extends ActiveController
{
Don't work.
Maybe this helps someone :)
This is my config/web.php:
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'urlManager'=>[
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'a',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;
And the controller:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController{
public $modelClass = 'app\models\User';
}
Also a created my model by gii.
The problem solved by enabling curl and using it in my controller.