PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

PHP OAuth Provider: Authenticate User

Note: This article was originally published at Planet PHP on 31 May 2011.
Planet PHP
I've been working with OAuth, as a provider and consumer, and there isn't a lot of documentation around it for PHP at the moment so I thought I'd share my experience in this series of articles. This relates to the stable OAuth 1.0a spec, however OAuth2 has already started to be adopted (and differs greatly). This article uses the pecl_oauth extension and builds on Rasmus' OAuth Provider post. This post is the third in the series, following on from the ones about the initial requirements and how to how to handle request tokens.

This phase is probably the most familiar to us as developers, as it's simply a login form. The consumer will send the user to us at the URL we provided in the request token, and the user will have the request token key as a parameter. The access control on this page will look the same as on the rest of the website; if the user has a session already then the page is displayed, otherwise they must be logged in to see it.

Request Token Verify



First of all we need to be sure that the request token that has been supplied is valid. For me, the code looks something like this:

A A A A $sql = 'SELECT request_token FROM oauth_request_tokens
A A A A A A WHERE request_token = ' . $this-db-escape($token) . '
A A A A A A AND authorised_user_id IS NULL';
A A A A $query = $this-db-query($sql);

A A A A $result = $query-result();
A A A A if(count($result) 0) {
A A A A A A return true;
A A A A }
A A A A return false;
A
Request tokens can only be used once, so if there is already a user associated with this one, something is wrong and we should not accept it. If the token exists and is awaiting user information, then that's all good and we can go ahead.

Grant or Deny



Once we know who the user is and we've checked the token, we present them with the option to grant or deny the access that is being requested. In my system, I put the request token in the user's session, rather than putting it to the form and then accepting it back again, just so I can be sure that nothing unexpected is happening. Depending on whether the user accepts or not, we will take different action.

Truncated by Planet PHP, read more at the original (another 13781 bytes)