3

I am trying to get a basic working foundation for a Lumen + Dingo Rest API, but I am not able to figure out how to peace is all together.

Lumen is working fine, but when I try to add Dingo I get all sorts of errors. From the Dingo documentation I read:

Once you have the package you can configure the provider in your config/api.php file or in a service provider or bootstrap file.

'jwt' => 'Dingo\Api\Auth\Provider\JWT'

or

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
   return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

I have installed a fresh copy of Lumen, and I do not see any config/api.php, so I assume I work with the piece of code to place in my bootstrap/app.php

Well this is what my bootstrap/app.php looks like:

<?php

require_once __DIR__.'/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->register(Dingo\Api\Provider\LumenServiceProvider::class);

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
    return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

$app->group(['namespace' => 'App\Api\Controllers'], function ($app) {
    require __DIR__.'/../app/Api/routes.php';
});

return $app;

When running this I get the following error:

BindingResolutionException in Container.php line 752:

Target [Tymon\JWTAuth\Providers\JWT\JWTInterface] is not instantiable while building [Tymon\JWTAuth\JWTAuth, Tymon\JWTAuth\JWTManager].

in Container.php line 752
at Container->build('Tymon\JWTAuth\Providers\JWT\JWTInterface', array()) in Container.php line 633
at Container->make('Tymon\JWTAuth\Providers\JWT\JWTInterface', array()) in Application.php line 205
at Application->make('Tymon\JWTAuth\Providers\JWT\JWTInterface') in Container.php line 853
at Container->resolveClass(object(ReflectionParameter)) in Container.php line 808
at Container->getDependencies(array(object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter)), array()) in Container.php line 779
at Container->build('Tymon\JWTAuth\JWTManager', array()) in Container.php line 633
at Container->make('Tymon\JWTAuth\JWTManager', array()) in Application.php line 205
at Application->make('Tymon\JWTAuth\JWTManager') in Container.php line 853
at Container->resolveClass(object(ReflectionParameter)) in Container.php line 808
at Container->getDependencies(array(object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter)), array()) in Container.php line 779
at Container->build('Tymon\JWTAuth\JWTAuth', array()) in Container.php line 633
at Container->make('Tymon\JWTAuth\JWTAuth', array()) in Application.php line 205
at Application->make('Tymon\JWTAuth\JWTAuth') in Container.php line 1178
at Container->offsetGet('Tymon\JWTAuth\JWTAuth') in app.php line 95
at {closure}(object(Application))
at call_user_func(object(Closure), object(Application)) in Auth.php line 216
at Auth->extend('jwt', object(Closure)) in app.php line 96
at require('/vagrant/dev_src/api/bootstrap/app.php') in index.php line 14

Only when I remove the following piece of code it works again:

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
    return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

UPDATE 1

.env file:

APP_ENV=local
APP_DEBUG=true
APP_KEY=xxxxSECRETxxxx

CACHE_DRIVER=file
QUEUE_DRIVER=sync

JWT_SECRET=yyyySECRETyyyy

API_VENDOR=MyCompanyName
API_STANDARDS_TREE=vnd
API_PREFIX=api
API_VERSION=v1
API_NAME="MyCompanyName API"
API_CONDITIONAL_REQUEST=false
API_STRICT=false
API_DEFAULT_FORMAT=json
patricus
  • 59,488
  • 15
  • 143
  • 145
Saif Bechan
  • 16,551
  • 23
  • 83
  • 125

1 Answers1

7

There's a lot you must to do. Here's the guide:

You have to manually bind the CacheManager implementation:

$app->singleton(
    Illuminate\Cache\CacheManager::class,
    function ($app) {
        return $app->make('cache');
    }
);

You also need to bind AuthManager implementation:

$app->singleton(
    Illuminate\Auth\AuthManager::class,
    function ($app) {
        return $app->make('auth');
    }
);

Before you register Dingo\Api\Provider\LumenServiceProvider, you have to register Tymon\JWTAuth\Providers\JWTAuthServiceProvider.

$app->register(Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
$app->register(Dingo\Api\Provider\LumenServiceProvider::class);

Before you register Tymon\JWTAuth\Providers\JWTAuthServiceProvider you need to make a config_path function, since Lumen doesn't support this global function.

/**
 * Because Lumen has no config_path function, we need to add this function
 * to make JWT Auth works.
 */
if (!function_exists('config_path')) {
    /**
     * Get the configuration path.
     *
     * @param string $path
     *
     * @return string
     */
    function config_path($path = '')
    {
        return app()->basePath().'/config'.($path ? '/'.$path : $path);
    }
}

Here's my full bootstrap/app.php file:

<?php

require_once __DIR__.'/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

$app->withFacades();

$app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Routing\ResponseFactory::class,
    Illuminate\Routing\ResponseFactory::class
);

$app->singleton(
    Illuminate\Auth\AuthManager::class,
    function ($app) {
        return $app->make('auth');
    }
);

$app->singleton(
    Illuminate\Cache\CacheManager::class,
    function ($app) {
        return $app->make('cache');
    }
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

// $app->middleware([
//    App\Http\Middleware\ExampleMiddleware::class
// ]);

// $app->routeMiddleware([
//     //
// ]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register(App\Providers\AppServiceProvider::class);
// $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);

// JWTAuth Dependencies
/**
 * Because Lumen has no config_path function, we need to add this function
 * to make JWT Auth works.
 */
if (!function_exists('config_path')) {
    /**
     * Get the configuration path.
     *
     * @param string $path
     *
     * @return string
     */
    function config_path($path = '')
    {
        return app()->basePath().'/config'.($path ? '/'.$path : $path);
    }
}

$app->register(Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
$app->register(Dingo\Api\Provider\LumenServiceProvider::class);

$app->make(Dingo\Api\Auth\Auth::class)->extend('jwt', function ($app) {
    return new Dingo\Api\Auth\Provider\JWT(
        $app->make(Tymon\JWTAuth\JWTAuth::class)
    );
});

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->group(['namespace' => App\Api\Controllers::class], function ($app) {
    require __DIR__.'/../app/Api/routes.php';
});

return $app;

Update 1

I make a simple POC using Lumen with Dingo API here.

whoan
  • 8,143
  • 4
  • 39
  • 48
krisanalfa
  • 6,268
  • 2
  • 29
  • 38
  • Man that is some nice effort you put into it, and also made a git repo, highly appreciated! I will make a clone of the repo and use it as the base of my API, thank you very much! – Saif Bechan Mar 25 '16 at 12:49
  • One question. In your repo I see you have a .env.example file, and some config files in /config. To configure Dingo, should I use the .env file, or the config files, or both. – Saif Bechan Mar 25 '16 at 13:12
  • Lumen still using `.env` file tho. I push config file for learning purpose only and other configuration which doesn't determined by `.env` file; like `auth.guards`, `api.errorFormat`, etc. – krisanalfa Mar 25 '16 at 13:16
  • Ok, that's clear. I have used the .env file, and set up the correct vars. Edited my main topic post. Only now when I browse to `http://localhost:8080/api/` I get a `403` page. All permissions of files are fine. – Saif Bechan Mar 25 '16 at 14:11
  • Strange. Mine is fine, I tried to clone the repo, did `composer install` and copy-paste your `.env` file, and got no issue. http://snag.gy/cD5Zb.jpg Any error in `lumen.log` you can provide? Better if you attach your `403` screenshot here. – krisanalfa Mar 25 '16 at 14:52
  • Yes I am sorry, this has something to do with my `nginx` config. It did not allow the `api/` path, only the `api/xxx` paths. My bad, thanks again for all the help! – Saif Bechan Mar 29 '16 at 09:54
  • This is working fine now. I am trying to load in my own framework here, and not working with Eloquent, but I am not really sure on how to set this up neatly. Maybe you have some tips to get me started. Here is the question: http://stackoverflow.com/questions/36283986/lumen-custom-authentication-without-eloquent – Saif Bechan Mar 29 '16 at 12:16
  • I'll answer it after I get my computer. – krisanalfa Mar 29 '16 at 12:24
  • 1
    I am building a RESTful app using Lumen. I face same problems and many other things. So, I wrap them up in this [article](http://excitingthing.com/blog/2016/04/08/lumen-5-2-and-things-you-should-be-noticed/). I hope you can find it's useful. I am still testing the integration with some of the work that I have done inside Lumen. If I found more things, I will keep update that post. – Tran Dang Khoa Apr 08 '16 at 08:04