Search code examples
javascriptsymfonyfosuserbundlefosrestbundlefosoauthserverbundle

How to access my new Symfony API


I've managed to combine FOSUserBundle, FOSOAuthServerBundle, and FOSRestBundle. I've created a client, and I've created a UserController. I've got my first route

http://domain.remote/api/users [ GET list users ].

OAuth is working, I get a "access denied" message. I'd like to write some javascript code that accesses this api, but I'm afraid I don't even know where to begin.

Can someone give me some explanation on how to authenticate and access my new Symfony API? Any examples would be very helpful. Preferably with no JS framework in mind so I can grasp the concept.

[Edit]

Some addition info. The JS code I'm writing will have users log in with their user name / password, and then manage their data with the API working behind the scenes.


Solution

  • Is your endpoint /api/users a secured endpoint? Check your security.yml file what kind of authorization you need to acces this endpoints. For example:

    api:
            pattern:    ^/
            security: true
    

    The code above means all your api url's are secured and need an authenticated user to access it. You'll need to access security context to log your user in. The most common approach to deal with authentication in REST api's is to use the OAuth method, preferably the OAuth2 method. I suggest you use FOSOAuthServerBundle to deal with OAuth2.

    After installing the bundle, you'll need to create 4 entities (accesstoken, authcode, client, refreshtoken) and your api workflow will be like this:

    1. Each of your devices (mobile app, desktop, for eg.) will have one client_id and client_secret.
    2. You'll request a token to your api, using FOSOAuthServerBundle token endpoint (/oauth/v2/token) passing the grant type (type of authentication, you can customize later) and data, for example: oauth/v2/token?client_id=<client_id>&client_secret=<client_secret>&grant_type=password&password=abc123&username=<yourlogin>
    3. If login credentials are valid, api will return a access token that you'll use to all your subsequent requests: http://domain.remote/api/users?access_token? Njc4NTA0MzQ3ZjE4MTBlOWU5ZGUxYTQ2ZWE3N2I2YzM4MzFjODcxMDdkYTU0MzIwOWE4Zjg4OGRiZWNjOTg2NQ

    This will allow you to make authorized requests to your api. You can refer to FOSOAuthServerBundle documentations for further details.

    Hope it helps.