Identifier "jwt" is not defined


#1

I am having an issue after running and getting a login token trying to access /api/

I get this error:
!My ERROR!

Slim Application Error

The application could not run because of the following error:
Details
Type: Slim\Exception\ContainerValueNotFoundException
Message: Identifier “jwt” is not defined.
File: /Users/hanifeoglu/Sites/slim-framework3-jwt/vendor/slim/slim/Slim/Container.php
Line: 120

Any ideas? I did more file comparisons between what I have an what you had above, but saw no easy answers why it wouldn’t work.

my Container.php

        <?php
        /**
         * Slim Framework (https://slimframework.com)
         *
         * @link      https://github.com/slimphp/Slim
         * @copyright Copyright (c) 2011-2017 Josh Lockhart
         * @license   https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
         */
        namespace Slim;
        use Firebase\JWT\JWT;
        use Interop\Container\ContainerInterface;
        use Interop\Container\Exception\ContainerException;
        use Pimple\Container as PimpleContainer;
        use Slim\Exception\ContainerValueNotFoundException;
        use Slim\Exception\ContainerException as SlimContainerException;


        /**
         * Slim's default DI container is Pimple.
         *
         * Slim\App expects a container that implements Psr\Container\ContainerInterface
         * with these service keys configured and ready for use:
         *
         *  - settings: an array or instance of \ArrayAccess
         *  - environment: an instance of \Slim\Interfaces\Http\EnvironmentInterface
         *  - request: an instance of \Psr\Http\Message\ServerRequestInterface
         *  - response: an instance of \Psr\Http\Message\ResponseInterface
         *  - router: an instance of \Slim\Interfaces\RouterInterface
         *  - foundHandler: an instance of \Slim\Interfaces\InvocationStrategyInterface
         *  - errorHandler: a callable with the signature: function($request, $response, $exception)
         *  - notFoundHandler: a callable with the signature: function($request, $response)
         *  - notAllowedHandler: a callable with the signature: function($request, $response, $allowedHttpMethods)
         *  - callableResolver: an instance of \Slim\Interfaces\CallableResolverInterface
         *
         * @property-read array settings
         * @property-read \Slim\Interfaces\Http\EnvironmentInterface environment
         * @property-read \Psr\Http\Message\ServerRequestInterface request
         * @property-read \Psr\Http\Message\ResponseInterface response
         * @property-read \Slim\Interfaces\RouterInterface router
         * @property-read \Slim\Interfaces\InvocationStrategyInterface foundHandler
         * @property-read callable errorHandler
         * @property-read callable notFoundHandler
         * @property-read callable notAllowedHandler
         * @property-read \Slim\Interfaces\CallableResolverInterface callableResolver
         */
        class Container extends PimpleContainer implements ContainerInterface
        {
            /**
             * Default settings
             *
             * @var array
             */
            private $defaultSettings = [
                'httpVersion' => '1.1',
                'responseChunkSize' => 4096,
                'outputBuffering' => 'append',
                'determineRouteBeforeAppMiddleware' => false,
                'displayErrorDetails' => false,
                'addContentLengthHeader' => true,
                'routerCacheFile' => false,
            ];

            /**
             * Create new container
             *
             * @param array $values The parameters or objects.
             */
            public function __construct(array $values = [])
            {
                parent::__construct($values);

                $userSettings = isset($values['settings']) ? $values['settings'] : [];
                $this->registerDefaultServices($userSettings);
            }

            /**
             * This function registers the default services that Slim needs to work.
             *
             * All services are shared - that is, they are registered such that the
             * same instance is returned on subsequent calls.
             *
             * @param array $userSettings Associative array of application settings
             *
             * @return void
             */
            private function registerDefaultServices($userSettings)
            {
                $defaultSettings = $this->defaultSettings;

                /**
                 * This service MUST return an array or an
                 * instance of \ArrayAccess.
                 *
                 * @return array|\ArrayAccess
                 */
                $this['settings'] = function () use ($userSettings, $defaultSettings) {
                    return new Collection(array_merge($defaultSettings, $userSettings));
                };

                $defaultProvider = new DefaultServicesProvider();
                $defaultProvider->register($this);
            }

            /********************************************************************************
             * Methods to satisfy Psr\Container\ContainerInterface
             *******************************************************************************/

            /**
             * Finds an entry of the container by its identifier and returns it.
             *
             * @param string $id Identifier of the entry to look for.
             *
             * @throws ContainerValueNotFoundException  No entry was found for this identifier.
             * @throws ContainerException               Error while retrieving the entry.
             *
             * @return mixed Entry.
             */
            public function get($id)
            {
                if (!$this->offsetExists($id)) {
                    throw new ContainerValueNotFoundException(sprintf('Identifier "%s" is not defined.', $id));
                }
                try {
                    return $this->offsetGet($id);
                } catch (\InvalidArgumentException $exception) {
                    if ($this->exceptionThrownByContainer($exception)) {
                        throw new SlimContainerException(
                            sprintf('Container error while retrieving "%s"', $id),
                            null,
                            $exception
                        );
                    } else {
                        throw $exception;
                    }
                }
            }

            /**
             * Tests whether an exception needs to be recast for compliance with Container-Interop.  This will be if the
             * exception was thrown by Pimple.
             *
             * @param \InvalidArgumentException $exception
             *
             * @return bool
             */
            private function exceptionThrownByContainer(\InvalidArgumentException $exception)
            {
                $trace = $exception->getTrace()[0];

                return $trace['class'] === PimpleContainer::class && $trace['function'] === 'offsetGet';
            }

            /**
             * Returns true if the container can return an entry for the given identifier.
             * Returns false otherwise.
             *
             * @param string $id Identifier of the entry to look for.
             *
             * @return boolean
             */
            public function has($id)
            {
                return $this->offsetExists($id);
            }


            /********************************************************************************
             * Magic methods for convenience
             *******************************************************************************/

            public function __get($name)
            {
                return $this->get($name);
            }

            public function __isset($name)
            {
                return $this->has($name);
            }
        }

#2

Use Markdown to format the source code. Then others can read and understand the code better.


#3

Just noting I edited the post to format the code.


#4

thank you @odan
i m used this is tutorial https://arjunphp.com/secure-web-services-using-jwt-slim3-framework/

i try to upload to same code here but zip file not give to access for upload

thank you
salih


#5

Open the src/settings.php file and append the followign JWT setttings array to existing settings array.

// jwt settings
"jwt" => [
    'secret' => 'supersecretkeyyoushouldnotcommittogithub'
]

#6

Hi thank you again @odan

have jwt seetting in my settings php

my src/settings.php

<?php
return [
    'settings' => [
        'displayErrorDetails' => true, // set to false in production
        'addContentLengthHeader' => false, // Allow the web server to send the content-length header

        // Renderer settings
        'renderer' => [
            'template_path' => __DIR__ . '/../templates/',
        ],

        // Monolog settings
        'logger' => [
            'name' => 'slim-app',
            'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
            'level' => \Monolog\Logger::DEBUG,
        ],

        "db" => [
            "host" => "127.0.0.1",
            "dbname" => "arjunphp_jwt_auth",
            "user" => "root",
            "pass" => "root"
        ],

        // jwt settings
        "jwt" => [
            'secret' => 'supersecretkeyyoushouldnotcommittogithub'
        ]
    ],
];

#7

I’ve tried the tutorial for you. There are some outdated examples:

This line is not correct…

"error" => function ($request, $response, $arguments) {

and must be changed to

"error" => function ($response, $arguments = []) {

#8

Hi @odan thank you for help

i change it
my middleware.php for your like code but not sol same problem continue


#9

@odan Did you test it your self environment ? sample code? and working ?