lexik / LexikJWTAuthenticationBundle

JWT authentication for your Symfony API
MIT License
2.53k stars 610 forks source link

Invalid JWT Token #221

Closed huggy06 closed 8 years ago

huggy06 commented 8 years ago

Hi,

I got this error and I don"t know how to resolve it, after login with success and obtain a token ( Im using SF2.8, FOSUserBundle)

{ "code": 401, "message": "Invalid JWT Token" } I made GET request to http://localhost:8000/app_dev.php/api/search with Authorization: Bearer "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJleHAiOjIzMzU2MjMzMDEsInVzZXJuYW1lIjoibWFyaW9uQGdtYWlsLmNvbSIsImlhdCI6IjE0NzE2MjMzMDEifQ."

Here is my security.xml

encoders:
        Symfony\Component\Security\Core\User\User: sha512
        FOS\UserBundle\Model\UserInterface: sha512
        MyLove\CoreBundle\Entity\User: sha512

providers:
        fos_userbundle:
            id: fos_user.user_provider.username

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

        login:
            pattern:  ^/api/login
            provider:  fos_userbundle
            stateless: true
            anonymous: true
            form_login:
                username_parameter:       email
                password_parameter:       password
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

        api:
            pattern:   ^/api
            provider:  fos_userbundle
            stateless: true
            lexik_jwt:
                authorization_header: # check token in Authorization Header
                    enabled: true
                    prefix:  Bearer
                    name:    Authorization
                query_parameter:
                    enabled: true
                    name:    bearer
 access_control:

        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

Any idea ?

Thanks

chalasr commented 8 years ago

Hello @huggy06,

Thank you for opening this issue. This feels more like a support related issue rather than a bug on this bundle. It could be more adapted to ask a question on stackoverflow using our lexikjwtauthbundle tag.

However, being quite familiar with using FOSUB as provider for this bundle, I'll dig into your issue and be back to confirm an eventual bug or, if it appears that the issue come from your side (server, ...), trying to give you some thoughts about the origin of the issue and how to fix it.

Keep you informed as soon as possible

huggy06 commented 8 years ago

Ho thanks for reply. It's a blocking point for us. We tested on windows and Linux with Apache.

Regards

chalasr commented 8 years ago

Something that could be very very useful for us in order to help you would be to create a fresh fork of the Symfony standard edition with the very same security configuration as your own app. So I could check it out and immediately say you if the problem come from our side.

Let me know if it can be envisaged for you, otherwise I'll do my best for reproducing it using the informations you given (should be enough).

Spomky commented 8 years ago

I noted that your authorization header is Authorization: Bearer "your_JWT"

It should be Authorization: Bearer your_JWT (without quotes).

huggy06 commented 8 years ago

Yes I know I made some tests :

I use Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJleHAiOjIzMzU3MDcyNTgsInVzZXJuYW1lIjoibWFyaW9uQGdtYWlsLmNvbSIsImlhdCI6IjE0NzE3MDcyNTgifQ.

chalasr commented 8 years ago

Could you please give your configuration of the bundle itself (config.yml)?

huggy06 commented 8 years ago

Yes sure here is my config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }
    - { resource: sylius.yml }

# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: fr
    stripe.test_secret_key: sk_test_BQokikJOvBiI2HlWgH4olfQ2

framework:
    #esi:             ~
    translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    #serializer:      { enable_annotations: true }
    templating:
        engines: ['twig']
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
        handler_id:  session.handler.native_file
        save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"
    fragments:       ~
    http_method_override: true
    assets: ~

monolog:
    handlers:
       applog:
           type: stream
           path: /var/log/symfony.log
           level: info

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    globals:
        sitename: "Briser la glace"
        baseurl: http://www.briser-la-glace.fr

# Doctrine Configuration
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: "%kernel.root_dir%/data/data.db3"
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #     path:     "%database_path%"

    orm:
        auto_generate_proxy_classes: %kernel.debug%
        entity_managers:
            default:
                auto_mapping: true
                mappings:
                    gedmo_loggable:
                        type: annotation
                        prefix: Gedmo\Loggable\Entity
                        dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Entity"
                        is_bundle: false
                dql:
                    string_functions:
                        DAY: DoctrineExtensions\Query\Mysql\Day
                        MONTH: DoctrineExtensions\Query\Mysql\Month
                        YEAR: DoctrineExtensions\Query\Mysql\Year
                filters:
                    softdeleteable:
                        class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
                        enabled: true

stof_doctrine_extensions:
    orm:
        default:
            tree: true
            sluggable: true
            timestampable: true
            softdeleteable: true
            sortable: true
            loggable: true
    uploadable:
        validate_writable_directory: true

# Swiftmailer Configuration
swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:     { type: memory }

# Assetic Configuration
assetic:
    debug:          %kernel.debug%
    use_controller: false
    bundles:        [ MyLoveCoreBundle, MyLoveDatingBundle, MyLoveShopBundle]
    #java: /usr/bin/java
    filters:
        jpegoptim:
            bin: /usr/bin/jpegoptim
        less:
            #node: /usr/bin/node
            node: C:\Program Files\nodejs\node.exe
            #node_paths: [/usr/lib/node_modules]
            node_paths: [C:\Users\jerome\AppData\Roaming\npm\node_modules]
            apply_to: "\.less$"
        cssrewrite: ~
        #closure:
        #    jar: %kernel.root_dir%/Resources/java/compiler.jar
        yui_css:
            jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.8.jar
            apply_to: ~
        yui_js:
            jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.8.jar
            apply_to: ~
    twig:
        functions:
            jpegoptim: { output: jpeg_images/*.jpg }
    assets:
        bootstrap_css:
            inputs:
                - %kernel.root_dir%/Resources/less/bootstrap.less
            filters:
                - less
                - cssrewrite
            output: bundles/braincrafted/css/bootstrap.css

braincrafted_bootstrap:
    css_preprocessor: less
    output_dir: bundles/braincrafted
    assets_dir: %kernel.root_dir%/../vendor/twbs/bootstrap
    jquery_path: %kernel.root_dir%/../vendor/components/jquery/jquery.js
    #less_filter: less # "less", "lessphp" or "none"
    auto_configure:
        assetic: true
        twig: true
        knp_menu: true
        knp_paginator: true
    customize:
        variables_file: %kernel.root_dir%/Resources/less/variables.less
        bootstrap_output: %kernel.root_dir%/Resources/less/bootstrap.less
        bootstrap_template: BraincraftedBootstrapBundle:Bootstrap:bootstrap.less.twig

# FOSUser Configuration
fos_user:
    db_driver: orm
    firewall_name: main
    user_class: MyLove\CoreBundle\Entity\User
    group:
        group_class: Sylius\Component\User\Model\Group
    service:
        mailer: fos_user.mailer.twig_swift
        user_manager: my_love_core_user_manager
    from_email:
        address: %from_email_address%
        sender_name: %from_email_sender_name%
    registration:
        confirmation:
            enabled: false
        form:
            type: my_love_core_user_register
    profile:
        form:
            type: my_love_dating_account_main
            validation_groups:
                - Default

sylius_addressing:
    driver: doctrine/orm

# Filesystem abstraction layer.
knp_gaufrette:
    adapters:
        sylius_image:
            local:
                directory:  %kernel.root_dir%/../web/media/image
                create:     true
        weit_image:
            local:
                directory:  %kernel.root_dir%/../web/media/image
                create:     true
    filesystems:
        sylius_image:
            adapter: sylius_image
        weit_image:
            adapter: weit_image

liip_imagine:
    loaders:
        default:
            filesystem:
                data_root: %kernel.root_dir%/../web/media/image
  #  resolvers:
  #      default:
  #          web_path:
  #              web_root: %kernel.root_dir%/../web/media/image
                #cache_prefix: %kernel.root_dir%/../web/media/cacher # media/cache
    driver:               gd
    cache:                default
    data_loader:          default
    default_image:        null
    controller:
        filter_action:         liip_imagine.controller:filterAction
        filter_runtime_action: liip_imagine.controller:filterRuntimeAction     
    filter_sets:
        sylius_16x16:
            filters:
                thumbnail: { size: [16, 16], mode: outbound }
        sylius_50x40:
            filters:
                thumbnail: { size: [50, 40], mode: outbound }
        sylius_90x60:
            filters:
                thumbnail: { size: [90, 60], mode: outbound }
        sylius_200x200:
            filters:
                thumbnail: { size: [200, 200], mode: outbound }

        sylius_262x255:
            filters:
                thumbnail: { size: [265, 255], mode: outbound }
        sylius_310x300:
            filters:
                thumbnail: { size: [310, 300], mode: outbound }
        sylius_610x600:
            filters:
                thumbnail: { size: [610, 600], mode: outbound }
        sylius_gallery:
            filters:
                thumbnail: { size: [640, 480], mode: outbound }

        sylius_small:
            filters:
                thumbnail: { size: [120, 90], mode: outbound }
        sylius_medium:
            filters:
                thumbnail: { size: [240, 180], mode: outbound }
        sylius_large:
            filters:
                thumbnail: { size: [640, 480], mode: outbound }

        weit_25x25:
            filters:
                thumbnail: { size: [25, 25], mode: outbound }
        weit_30x30:
            filters:
                thumbnail: { size: [30, 30], mode: outbound }
        weit_50x50:
            filters:
                thumbnail: { size: [50, 50], mode: outbound }
        weit_75x75:
            filters:
                thumbnail: { size: [75, 75], mode: outbound }
        weit_160x160:
            filters:
                thumbnail: { size: [160, 160], mode: outbound }
        weit_240x240:
            filters:
                thumbnail: { size: [240, 240], mode: outbound }
        weit_260x260:
            filters:
                thumbnail: { size: [260, 260], mode: outbound }
        weit_320x320:
            filters:
                thumbnail: { size: [320, 320], mode: outbound }
        weit_320x400:
            filters:
                thumbnail: { size: [320, 400], mode: outbound }
        produitThumb:
            quality: 80
            filters:
                thumbnail: { size: [200, 200], mode: inset }
        produit:
            quality: 75
            filters:
                thumbnail: { size: [470, 310], mode: inset }

services:
    twig.extension.text:
       class: Twig_Extensions_Extension_Text
       tags:
            - { name: twig.extension }
    twig.extension.intl:
        class: Twig_Extensions_Extension_Intl
        tags:
            - { name: twig.extension }

blade_tester_calendar:
    driver: doctrine/orm
    engine: twig
    classes:
        event:
            entity: MyLove\CalendarBundle\Entity\Event
        category:
            entity: BladeTester\CalendarBundle\Entity\EventCategory

mremi_contact:
    store_data:            false
    contact_class:         Mremi\ContactBundle\Model\Contact

    form:
        type:              mremi_contact
        name:              contact_form
        validation_groups: [Default]
        subject_provider:  mremi_contact.subject_provider.noop

    email:
        mailer:            mremi_contact.mailer.twig_swift
        from:              
            - { address: support@briserlaglace.com, name: "Support" }
        to:                
            - { address: jerome.termes@gmail.com, name: "Webmaster" }
        template:          MremiContactBundle:Contact:email.txt.twig

my_love_comment:
    comment:
        default_status: "validated"
        from_email: "webmaster@mywebsite.fr"
        admin_email_list: ["admin@mywebsite.fr"]

fos_elastica:
    clients:
        default: { host: localhost, port: 9200 }
    indexes:
        mylove:
            client: default
            settings:
                index:
                    analysis:
                        analyzer:
                            custom_search_analyzer:
                                type: custom
                                tokenizer: standard
                                filter   : [standard, lowercase, asciifolding]
                            custom_index_analyzer:
                                type: custom
                                tokenizer: standard
                                filter   : [standard, lowercase, asciifolding, custom_filter]
                        filter:
                            custom_filter:
                                type: edgeNGram
                                side: front
                                min_gram: 1
                                max_gram: 20
            types:
                user:
                    mappings:
                        nickname: ~
                        email: ~
                        age:
                            type: integer
                        sex:
                            type: boolean
                        city: 
                            type: nested
                            properties:
                                ville: ~
                                location:
                                    type: geo_point
                                    lat_lon: true
                                id:
                                    type: integer
                    persistence:
                        driver: orm # orm, mongodb, propel are available
                        model:  MyLove\CoreBundle\Entity\User
                        provider: ~
                        listener: ~ #The list of the listeners for which the indexing is called (default : insert, update, delete. Used in most cases)
                        finder: ~
                city:
                    mappings:
                        id:
                           type: integer
                        ville:    { search_analyzer: custom_search_analyzer, index_analyzer: custom_index_analyzer, type: string }
                        cp: { type: string }
                    persistence:
                        driver: orm
                        model: MyLove\EcommerceBundle\Entity\City
                        provider: ~
                        finder: ~

genemu_form:
    autocomplete: ~
    select2: ~

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'
        formats:
            xml: true
            json : true
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig
    routing_loader:
        default_format: json

jms_serializer:
    metadata:
        auto_detection: true
        directories:
            FOSUB:
                namespace_prefix: FOS\UserBundle
                path: "@MyLoveCoreBundle/Resources/config/serializer"
            FOSUB:
                namespace_prefix: MyLove\CoreBundle
                path: "@MyLoveCoreBundle/Resources/config/serializer"

hwi_oauth:
    http_client:
        verify_peer: false
    # name of the firewall in which this bundle is active, this setting MUST be set
    firewall_name: main
    connect:
        account_connector: app.provider.oauth
    resource_owners:
        facebook:
            type:                facebook
            client_id:           %facebook_client_id%
            client_secret:       %facebook_client_secret%
            scope:               "email, public_profile, user_birthday"
            infos_url:           "https://graph.facebook.com/me?fields=id,name,email,first_name,last_name,gender,birthday,picture.type(large)"
            paths:
                email: email
            options:
                display: page

lexik_jwt_authentication:
    private_key_path: %jwt_private_key_path%
    public_key_path:  %jwt_public_key_path%
    pass_phrase:      %jwt_key_pass_phrase%
    token_ttl:        %jwt_token_ttl%
chalasr commented 8 years ago

@huggy06 Sorry for the delay. Before looking deeper into your config, I would like to know more about your User entity and which property is used to get the token (I see the username_parameter set to email that makes me guess you are expecting an email address instead of an username when getting the token). If the user sends its email to /api/login instead of the username, you have to:

Don't forget to renew the token each time you change this config. Let me know if it helps

chalasr commented 8 years ago

@huggy06 I'm going to close this issue in next days, did you solve your problem ?