Question

I have created a REST API, i'm actually trying to secure it with the FOSOAuthServerBundle.

I created the route newclient to generate new client, now i would like to allow only the 'admin' to access to this url.

I guess it's possible to do this with scopes but i can't figure out how.

Here is my security.yml:

security:

    providers:
        user_provider:
            id: user_provider

    firewalls:
        doc:
            pattern:    ^/doc
            security:   false

        oauth_token:
            pattern:    ^/oauth/v2/token
            security:   false

        oauth_authorize:
            pattern:    ^/oauth/v2/auth
            provider: user_provider
            anonymous:  true

        api:
            pattern:    ^/
            fos_oauth:  true
            stateless:  true
            anonymous:  false

    access_control:
        - { path: ^/, roles: ROLE_CLIENT }
        - { path: ^/newclient, roles: ROLE_ADMIN }

My config.yml

fos_oauth_server:

    db_driver: orm 
    client_class: WS\RESTBundle\Entity\Client
    access_token_class: WS\RESTBundle\Entity\AccessToken
    refresh_token_class: WS\RESTBundle\Entity\RefreshToken
    auth_code_class: WS\RESTBundle\Entity\AuthCode

Any tips ?

Was it helpful?

Solution

Actually desling with scopes is not the best way to do it, plus the bundle does not support it : https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/issues/231

I made use the User model, add a "role" method and check if the current user's role is enough to access the to the routes.

Here is the piece of code

//Get the current user, check if it's an admin
$token = $this->container->get('security.context')->getToken()->getToken();

$accessToken = $this->container
->get('fos_oauth_server.access_token_manager.default')
->findTokenBy(array('token' => $token));

$client = $accessToken->getClient();


if ($client->getRole() == 'admin') {

...
}

Not sure if it's the best way to do it, any advices welcome !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top