maxwell2022
maxwell2022

Reputation: 2855

How to build PHP API authentication with Facebook token and username/password

I'm building a very simple API using silex (php micro-framework). I have an idea on how to authenticate user using Facebook connect or username / password.

I want to build this API to provide data to my mobile app. My API is using HTTPS. The authentication with Facebook:

Now using login / password:

The question is about the user session. I don't really want to do this tests on every requests (ie. for Facebook auth there is 2 requests to Facebook).

I was thinking to open a session for the user and store some kind of API token. The token would be hashed and salted (salt + user_id + time delivered). I would store it in the session table and would only need to check that the token is still valid and belong to the requesting user.

So the mobile app would only send the user id + the api token for every request.

What to you think of it ? Do you thing of a better solution keeping it simple? Or do you see any issue with this design?

Cheers, Maxime

Upvotes: 0

Views: 783

Answers (2)

user3280814
user3280814

Reputation: 1

You can save the Facebook Id in the first user login. Then after check for active facebook user you can search and compare in Mysql for existent facebook Id.

Upvotes: 0

Jasper N. Brouwer
Jasper N. Brouwer

Reputation: 21827

Facebook's authentication flows are based on the OAuth 2.0 protocol. More information about the protocol can be found here.

The flow follows these general steps:

  • Determine whether someone is already logged in.
  • If they aren't logged in, prompt them to do so (with a login dialog).
  • Exchange secure codes to confirm identity.
  • Generate an access token.

Once your client has obtained the access token, it should store that token. The client can then perform API requests on the user's behalf using the access token. So there's no need to follow the steps above again once you have the access token (unless that token has expired).

Facebook provides a number of SDKs for you to use, including a couple of mobile SDKs. I suggest you use an appropriate SDK for your mobile app. Implementing an OAuth 2.0 dialog with Facebook will be much easier than doing everything manually. Start reading here.

Upvotes: 1

Related Questions