I have recently setup an API using the FOSUser FOSOAuthServer and FOSRest Bundles.
In my security.yml I have the following:
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
oauth_token: # Everyone can access the access token URL.
pattern: ^/login
security: false
api:
pattern: / # All URLs are protected
fos_oauth: true # OAuth2 protected resource
stateless: true # Do no set session cookies
anonymous: false
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
This allows anonymous access to the login route while every other route requires Authentication.
I have created a login route that proxies the request over to the OAuth Client. This way the user never knows the client secret: (note i have removed the client id and secret in the example)
/**
* @Post("/login")
*/
public function postLoginAction(Request $request){
$request->request->add( array(
'grant_type' => 'password',
'client_id' => 'clientID_clientRandomID',
'client_secret' => 'clientSecret'
));
return($this->get('fos_oauth_server.controller.token')->tokenAction($request));
}
This will return the OAuth Token if valid user/pass is submitted.
Once I have this token I can add it to the Headers for any requests
Authorization: Bearer OAuth_TOKEN
Once the user is validated you can always check their roles, if needed, in any api calls. Something like the following:
public function getUserAction()
{
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
$user = $this->getUser();
$view = $this->view($user);
return $this->handleView($view);
}
Another approach for checking roles could be done in security.yml
# app/config/security.yml
security:
# ...
access_control:
- path: "^/api/users/\d+$"
allow_if: "'DELETE' == request.getMethod() and has_role('ROLE_ADMIN')"
I found this in the following post: RESTFul OAuth with FOSOAuthServer / FOSRest & FOSUser
This is how I approached things for a Symfony3 build, some syntax (checking a user role) may be different for Symfony2
I used this post as a reference while building my api: http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/