Search code examples
symfony4api-platform.com

Session based authentication in api-platform


I am trying to setup session based authentication instead of JWT that I have currently in use, because I don´t want to store JWT token in local storage.

I have managed to authenticate myself using this guide https://symfony.com/doc/current/security/json_login_setup.html and get response data about the user.

But further requests to any endpoint I get 401 unauthorized.

This is my security yaml

security:
encoders:
    App\Entity\User:
        algorithm: bcrypt
providers:
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email
firewalls:
    dev:
        pattern: ^/_(profiler|wdt)
        security: false
    api:
        pattern: ^/api/
        stateless: true
        anonymous: true
        provider: app_user_provider
        json_login:
            check_path: /api/login
            username_path: email
            password_path: password
            #success_handler: lexik_jwt_authentication.handler.authentication_success
            #failure_handler: lexik_jwt_authentication.handler.authentication_failure

        #guard:
        #   authenticators:
        #      - lexik_jwt_authentication.jwt_token_authenticator
    main:
        anonymous: true
access_control:
    - { path: ^/api/authentication_token,   roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/graphql,                roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/form/,                  roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/,                       roles: IS_AUTHENTICATED_FULLY }
    - { path: ^/,                           roles: IS_AUTHENTICATED_ANONYMOUSLY }

On the official api-platform documentation there is no word of using session based login which I find odd.

Thank you


Solution

  • You need to remove stateless: true or change it to stateless: false

    The stateless configuration parameter prevents Symfony from trying to store the authentication information in the session

    All else looks good to me, however if this does not solve your issue can you add any message that is returned with the 401 response code to you queston?