PHP Consuming RESTful APIs
Making an OAuth 1.0 Request
Problem
You want to make an OAuth 1.0 signed request.
Solution
Use the PECL oauth extension.
Discussion
OAuth 1.0 enables API providers to let their users securely give third-party developers access to their accounts by not providing their usernames and passwords.
Instead, you use two sets of public and private tokens to sign your requests. One set of tokens is for your application; that’s used for every request. The other set is user specific; they differ from user to user.
You pass along the two public tokens to identify your application and the user. You also use the two private tokens, also called secrets, to sign the request. The signature is constructed using the HTTP method and URL of the request, along with a few other pieces of metadata, such as a timestamp.
When the request is received, the API provider validates the signature and other pieces of the request to ensure its legitimacy. Because only you and the provider have these secret keys, the API provider knows that if the signatures match the request must have come from the you. If they disagree, then it’s a fake and should be rejected.
Using the PECL oauth extension, you don’t need to worry about the specifics of the algorithm itself. What you need to know instead is the general authorization flow, nicknamed the OAuth Dance:
1. You get an initial set of user tokens. These are also called request tokens or temporary tokens, because they’re only used during the authorization process and not to make actual API calls.
2. You redirect the user to the API provider.
3. The user signs into that site, which authenticates the user and asks him to authorize your application to make API calls on his behalf.
4. After the user authorizes your application, the API provider redirects the user back to your application, passing along two pieces of data: the same temporary public key you provided to match up each reply with its corresponding user and a PIN to prevent against session fixation attacks.
5. You exchange the PIN for permanent OAuth tokens for the user.
6. You make API calls on behalf of the user.
The “Hello World” example from the Solution uses LinkedIn’s REST APIs to greet the user with his first name.
For other API providers, the OAuth flow is the same, but you will need to alter URLs at the top of the example and the API call itself.
No comments:
Post a Comment