3

On my symfony2 project, I'm using FOSUSerBundle for login, register, etc on a Website. Works fine, as I expected. But now I'd like to build a REST API, so that a android app can act as client to and work with the data. I found FOSRestBundle to build the REST API inside the symfony2 Project. I want to use FOSOAuthServerBundle for handle the tokens for accessing the api. The User should login via the API and then he can user other methods provided by the api.

I read a lot of Blogs and other documentation, but can't find, how to build the REST Api. I set up each Bundle and I generated a Client with a public ID and the secure code. Over the Website I can use the login.

But what steps / methods will I have to define in mein REST API Controller to use the token auth?

Thank you!

user3460622
  • 165
  • 1
  • 11

2 Answers2

0

In this link, you will find a good example for developing your first REST api.

Good luck.

Amine Jallouli
  • 3,919
  • 8
  • 36
  • 73
0

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/

Community
  • 1
  • 1
Shawn Northrop
  • 5,826
  • 6
  • 42
  • 80
  • The proxy part is literally the only piece of code I've found that shows how to use oauth with only user/password while keeping the client id and client secret hidden from public. – Tek Dec 10 '16 at 20:12
  • Yea, seemed like a pretty simple concept that no one had implemented. Keeping the client secret a secret. – Shawn Northrop Dec 21 '16 at 06:43