Search code examples
symfonyoauthfosoauthserverbundle

Symfony FOSOAuthServerBundle: access token not detected


I'm using FOSOAuthServerBundle as my oauth endpoint. I succesfully generated a token using the Resource Owner Password Credentials grant method:

{
    "access_token": "MY-FOO-TOKEN",
    "expires_in": ​3600,
    "token_type": "bearer",
    "scope": "read",
    "refresh_token": "MY-BAR-REFRESH-TOKEN"
}

Now I would like to use it to get some protected resources. So I did:

curl -X GET -H "Authorization: Bearer MY-FOO-TOKEN" "http://localhost:8000/api/a-bar-resource"

The Bearer do not seem to be detected.


INFOS:

echo $this->get('security.token_storage')->getToken(); gives: AnonymousToken(user="anon.", authenticated=true, roles="")

In the headers there is:

["authorization"]=> /** <-- Is the lowercase OK? **/
  array(1) {
    [0]=>
    string(93) "Bearer MY-FOO-TOKEN"
  }

I also tried to pass access_token as a query parameter, without success.

Now I'm guessing something is wrong with the config.yml or the security.yml. Here are some selected parts:

config.yml:

fos_oauth_server:
[...]
    service:
        options:
            supported_scopes: read
        user_provider: fos_user.user_provider.username_email

security.yml:

security:
[...]
    firewalls:
        api:
            pattern:    ^/api
            fos_oauth:  true
            stateless:  true
            anonymous:  false
    access_control:
            - { path: ^/api, roles: [ IS_AUTHENTICATED_ANONYMOUSLY ] }

Solution

  • I finally found what was causing the problem. I had a firewall that was nullifying the other firewall, because of same patterns:

    security:
    [...]
        firewalls:
            other_firewall: #this one
                pattern:    ^/
                anonymous:  true
            api:
                pattern:    ^/api
                fos_oauth:  true
                stateless:  true
                anonymous:  true
    

    I also think that an authentication made in one firewall is not available in an other firewall, so diminishing the number of firewalls to the strict minimum (one not secured, one with auth etc.) is a good practice. Then using access_control for fine access.