Search code examples
phpsymfonybasic-authenticationfosrestbundle

FOSRestBundle add http basic auth


I added FOSRestBundle to my symfony2 app, this app already had a public area and an admin area protected by FOSUserBundle.

My problem is, I don't get browser to prompt for user/password and also, when connecting api with curl I don't get authorized.

# app/config/security.yml
providers:
    user:
        id: fos_user.user_provider.username
    administrator:
        entity: { class: App\UserBundle\Entity\Administrator, property: login }

Now I added an api area and want to use basic http auth, so added a new provider

    api_provider:
        memory:
            users:
                user1: { password: 1234, roles: 'ROLE_API_USER' }
                user2: { password: 1234, roles: 'ROLE_API_USER' }

And a new firewall:

firewalls:
    backend:
        pattern:        ^/admin/
        provider:       administrator
        anonymous:      ~
        form_login:
            login_path: /admin/login
            check_path: /admin/login_check
        logout:
            path:       /admin/logout
            target:     /admin/
    api:
        pattern:  ^/api/
        provider: api_provider
        anonymous: ~
        # form_login: false # <- needed or not?
        http_basic:
            realm: "Api"
    main:
        pattern: ^/
        form_login:
            login_path: /login
            check_path: /login_check
            provider: user
            csrf_provider: form.csrf_provider
        logout:       true
        anonymous:    true

At this point I leep getting a 403 - Forbidden, so if I add this so security.yml:

access_control:
    - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/user, role: ROLE_ADMIN_USUARIOS }
    - { path: ^/admin/, role: ROLE_ADMIN }
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/error, role: ROLE_USER }
    - { path: ^/api/, role: ROLE_API_USER }
    - { path: ^/api/v1/users, role: ROLE_API_USER }

After this I get a 401 - unauthorized.

I though http basic auth forced browser to prompt for a user/pass, which doesn't happen. Although, what I will finally need is the server to accept a basic auth header in http requests like this one.

I'm I missing something?

Thanks


Solution

  • SOLUTION

    Apparently the only way to invoke these urls now is through and http connection like curl adding authorization header, for example:

    curl -u "user:pass" "http://example.com/app_dev.php/api/v1/users/1.json"
    

    Accessing through the browser does not prompt for user/pass.

    Additionally, a encoder was needed for the new provider to work properly:

    # app/config/security.yml
    encoders:
        Symfony\Component\Security\Core\User\User: plaintext