1

I am trying to use LexikJWTAuthenticationBundle with Doctrine User management with API-Platform. After the configuration I always receive the {"code":401,"message":"JWT Token not found"}

1) I installed LexikJWTAuthenticationBundle as described in https://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/index.md , I changed routes.yaml to the path /login_check instead the /api/login_check

2) I generated the Entity User and used doctrine to generate the database table. Additionally I created the class UserRepository

3) I changed my security.yaml to

# app/config/packages/security.yaml
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_READER: ROLE_USER
        ROLE_ADMIN: ROLE_READER

    providers:
        users:
            entity:
                # the class of the entity that represents users
                class: 'App\Entity\User'
                # the property to query by - e.g. username, email, etc
                property: 'username'
                # optional: if you're using multiple Doctrine entity
                # managers, this option defines which one to use
                # manager_name: 'customer'

    firewalls:
        login:
            pattern:  ^/login
            stateless: true
            anonymous: true
            provider: users
            json_login:
                check_path: /login_check
                username_path: email
                password_path: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        main:
            pattern:   ^/
            provider: users
            stateless: true
            anonymous: true
            guard:
                authenticators:
                - lexik_jwt_authentication.jwt_token_authenticator

        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

    access_control:
    - { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/books, roles: [ ROLE_READER ] }
    - { path: ^/, roles: [ ROLE_READER ] }

Furthermore I changed the api_platform.yaml to

parameters:
    # Adds a fallback VARNISH_URL if the env var is not set.
    # This allows you to run cache:warmup even if your
    # environment variables are not available yet.
    # You should not need to change this value.
    env(VARNISH_URL): ''

api_platform:
    swagger:
        api_keys:
            apiKey:
                name: Authorization
                type: header
    mapping:
        paths: ['%kernel.project_dir%/src/Entity']
    title: Hello API Platform
    version: 1.0.0
    #Varnish integration, remove if unwanted
#    http_cache:
#        invalidation:
#            enabled: true
#            varnish_urls: ['%env(VARNISH_URL)%']
#        max_age: 0
#        shared_max_age: 3600
#        vary: ['Content-Type', 'Authorization']
#        public: true
    # Mercure integration, remove if unwanted
    mercure:
        hub_url: '%env(MERCURE_SUBSCRIBE_URL)%'

The User looks like

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=60, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    public function __construct() // add $username
    {
        $this->isActive = true;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getSalt()
    {
        // you *may* need a real salt depending on your encoder
        // see section on salt below
        return null;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getRoles()
    {
        return array('ROLE_ADMIN');
    }

    public function eraseCredentials()
    {
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt
            ) = unserialize($serialized);
    }
}

If i use curl I receive the following error: Unable to find the controller for path "/login_check". The route is wrongly configured. (404 Not Found)

Where is my mistake? Thanks in advance.

Ludi
  • 77
  • 1
  • 1
  • 8
  • What did you add to routes.yml? Do you get a 401 or 404 error message? Seems strange to me if you get both, could you elaborate where how you get to these? Did you check this [Question](https://stackoverflow.com/questions/49282372/api-platform-jwt-no-route-found-for-get-api-login?rq=1), could be a duplicate? – Thomas Vangelooven Apr 14 '19 at 08:31
  • The content of routes,yml is `login_check: path: /login_check methods: [POST]` I already read the linked post, but didn't find a solution for my problem. When I added Content-Type: application/json to the request I receive the response "code": 401, "message": "Bad credentials" It seam that my stored password is wrong and the swagger has a problem with my authentication – Ludi Apr 14 '19 at 10:43
  • So I take it you have set a new password and tried again? Same error? Maybe you can share the implemented methods from `UserInterface` in your `User` entity class? – Thomas Vangelooven Apr 14 '19 at 12:31
  • I just added the User entity class to my question above. – Ludi Apr 14 '19 at 17:37

1 Answers1

0

If you use Apache and you have {"code": 401, "message": "JWT token not found"}, the problem may be your rewriting rules in your virtual host. In my case, I remove the rewrite rules from my virtual host and I add my missing .htaccess in the /public folder (Symfony 4)

PS: /web folder for Symfony <4


SEE Lexik JWT Token not found

gregoireskazy
  • 96
  • 2
  • 4