2

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.

Theodore Enderby
  • 622
  • 1
  • 6
  • 19

2 Answers2

1

KNP has really detailed tutorials about this. Please have a look at this tutorial. List of all API tutorials can be found here

Shairyar
  • 3,268
  • 7
  • 46
  • 86
1

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.

Hugo Nogueira
  • 1,298
  • 1
  • 12
  • 24
  • Thanks for your answer. I'm understanding more and more each time I work at it. I'm able to get my access token at this point, but I'm still having difficulty with what I believe are scopes. You see at this point, it doesn't matter what username and password I use and I still gain access to the API. – Theodore Enderby Aug 20 '15 at 16:55