Home > Backend Development > PHP Tutorial > PHP Master | Understanding OAuth - Tweeting from Scratch, Part 1

PHP Master | Understanding OAuth - Tweeting from Scratch, Part 1

Lisa Kudrow
Release: 2025-03-02 08:39:10
Original
245 people have browsed it

PHP Master | Understanding OAuth - Tweeting from Scratch, Part 1

Core points

  • OAuth is like a "valet key" that allows PHP applications to post to Twitter on behalf of users without having to enter a username and password every time. An application is a consumer, a user is a resource owner, and Twitter is a server or service provider.
  • To post information on Twitter, the application needs to obtain its own client credentials: the consumer key and the consumer key. Twitter grants these credentials after the application completes the registration form and provides information such as its name, description, website URL, and callback URL.
  • Consumer key and consumer key allow the application to communicate with the Twitter API, but to post tweets on behalf of the user, it also requires access credentials: access tokens and access keys. These are obtained by using consumer credentials to talk to Twitter and end users.
  • This article provides a detailed step-by-step guide on how to obtain these credentials, including the code required to generate the request credential URL, how to build a signature based on a string, and how to create a URL that requests access credentials.

Many people think that OAuth is difficult to understand, probably because people expect that the abstraction provided by third-party libraries will eliminate the need to understand OAuth transaction steps – but that is not the case. This article is divided into two parts, demonstrating how OAuth v1 works by connecting a PHP application to the Twitter API using only a few built-in functions to post messages to the user's Twitter stream. The sample code provided in this article is for educational purposes only. It lacks practical use and error handling, and any actual development should take advantage of the existing OAuth library, but after reading this article you will have a better understanding of how OAuth works and will be able to better solve any problems that may arise.

Get consumer credentials

Post to Twitter on behalf of the user without asking for a combination of username and password every time, it requires a "valet key"... This key is OAuth. In OAuth terms, your client application is called consumer, the user is called resource owner, and Twitter is a server or service provider. Before Twitter accepts information posted by your application, you need to obtain your own client credentials: Consumer Key and Consumer Key. Twitter (and most services that provide public APIs) grant you the key and key after you complete the registration form (available at dev.twitter.com/apps). On Twitter, you need to provide some information to identify your application, especially its name, description, and website URL, to users during the authorization process. You also need to enter the callback URL, which I will explain later. After submitting the Create Application form, you will be taken to the Details page of the new application. Scroll down to find your consumer key and key. You will need these keys along with a small number of endpoint URLs listed. Note that the application is granted read-only access by default; since it will post a tweet, you need to click on the Settings tab and change the access to Read and Write.

Authorized Application

Consumer keys and consumer keys allow your application to communicate with the Twitter API, but these keys alone cannot post tweets on behalf of other users. You need access credentials: Access token and Access key. To obtain these credentials by using consumer credentials to have a brief conversation with Twitter and end users, make a request to the service provider (Twitter). Getting access credentials can be quite cumbersome, but luckily you only need to do this once for each user. You can save credentials indefinitely for later use without the user reauthorizing your application. A conversation that requests access to credentials requires its own set of credentials: Request token and Request key.

Authorization Step 1: Request Credentials

The authorization process usually begins with directing the user to the "Authorization Twitter" page. This is the page you created that starts the request token from Twitter and starts the OAuth authorization process. It must generate a URL to get the requested credentials, and once you have the credentials, you can redirect the user to Twitter to grant the application publication permission. The request request credentials require a signature request, which means you need to send an OAuth signature along with other important parameters in the request. The signature is a base64 encoded hash list of requested parameters. In the case of Twitter, the hashing algorithm is HMAC-SHA1. The signature process prevents others from impersonating your application to use your credentials, even if the consumer key is transferred in plain text. Only you (the consumer) and the server (Twitter) can reproduce the signature, because you two are the only entities that should know the consumer key that hash the signature. Let's build a string on which the signature is based:

<?php
$requestTokenUrl = "http://api.twitter.com/oauth/request_token";
$authorizeUrl = "http://api.twitter.com/oauth/authorize";
$oauthTimestamp = time();
$nonce = md5(mt_rand());
$oauthSignatureMethod = "HMAC-SHA1";
$oauthVersion = "1.0";

$sigBase = "GET&" . rawurlencode($requestTokenUrl) . "&"
    . rawurlencode("oauth_consumer_key=" . rawurlencode($consumerKey)
    . "&oauth_nonce=" . rawurlencode($nonce)
    . "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
    . "&oauth_timestamp=" . $oauthTimestamp
    . "&oauth_version=" . $oauthVersion);
Copy after login
Copy after login

Some of the variables above may be quite obvious - $requestTokenUrl is taken from Twitter when you get the consumer credentials, and $oauthTimestamp is the current UNIX timestamp. The less obvious item is $nonce, which is nothing more than a random string that is used only once (each transaction uses a different nonce). Generally, MD5 hash random numbers are very useful as nonce. There is also $oauthSignatureMethod, which is always HMAC-SHA1 for Twitter, and $oauthVersion for Twitter, currently v1.0 for Twitter. Next, the signed string is constructed as $sigBase. OAuth points out that the signature base must be an HTTP method (in this case GET), followed by a "&" followed by a URL-encoded request URL ($requestTokenUrl), followed by another "&", and finally a URL-encoded and alphabetical list of parameter key/value pairs (whose values ​​must also be encoded), separated by a "&". Note that when OAuth requires URL-encoded content, it refers to RFC-3986. PHP's rawurlencode() function works because it encodes spaces as " , rather than " , like urlencode() does. You also need a signature key. The key is always a consumer key followed by a "&", and 1) an OAuth token key (which is part of the token credentials you don't have yet), or 2) nothing. You can then use PHP's built-in hash_hmac() function to generate the final signature.

<?php
$sigKey = $consumerSecret . "&";
$oauthSig = base64_encode(hash_hmac("sha1", $sigBase, $sigKey, true));
Copy after login
Copy after login

You put all the parts together to build a URL that requests the credentials:

<?php
$requestUrl = $requestTokenUrl . "?"
    . "oauth_consumer_key=" . rawurlencode($consumerKey)
    . "&oauth_nonce=" . rawurlencode($nonce)
    . "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
    . "&oauth_timestamp=" . rawurlencode($oauthTimestamp)
    . "&oauth_version=" . rawurlencode($oauthVersion)
    . "&oauth_signature=" . rawurlencode($oauthSig);

$response = file_get_contents($requestUrl);
Copy after login

You need more error handling for anything beyond this simple demo, but for now, I'm assuming that there won't be any errors and that you're able to receive temporary request credentials in $response . The response sent back by Twitter is as follows:

<code>oauth_token=mjeaYNdNYrvLBag6xJNWkxCbgL5DV6yPZl6j4palETU&oauth_token_secret=W45dnBz917gsdMqDu4bWNmShQq5A8pRwoLnJVm6kvzs&oauth_callback_confirmed=true</code>
Copy after login
The

oauth_token and oauth_token_secret values ​​are extracted from the response and are used to build the next link the user accesses in the second step of the authorization process. It is best to store the requested credentials in the user's session so that they can be used when the user returns from the authorization page of Twitter. Authorization URL is available on the Details page after registering your application using Twitter.

<?php
parse_str($response, $values);
$_SESSION["requestToken"] = $values["oauth_token"];
$_SESSION["requestTokenSecret"] = $values["oauth_token_secret"];

$redirectUrl = $authorizeUrl . "?oauth_token=" . $_SESSION["requestToken"];
header("Location: " . $redirectUrl);
Copy after login

Now that the app can send users to Twitter for authorization, it's a good time to add a callback URL so that Twitter can send them back to the app! The callback URL is nothing more than the address that Twitter directs the user to after the user authorizes your application to send a tweet on its behalf and is specified on the Settings tab of the Details page. When Twitter redirects the user to the callback URL, it appends two additional parameters: the oauth_token in your initial request, which can be used for verification, and the oauth_verifier, which can be used for authorization credentials. In the three credential sets you need to post a tweet, you now have two—consumer credentials and request credentials. Next: Access credentials!

Authorization Step 2: Access Credentials

To get access credentials, you need oauth_token, oauth_token_secret and newly obtained oauth_verifier. This step requires another signature request, this time for the access token URL displayed on the Details page.

<?php
$requestTokenUrl = "http://api.twitter.com/oauth/request_token";
$authorizeUrl = "http://api.twitter.com/oauth/authorize";
$oauthTimestamp = time();
$nonce = md5(mt_rand());
$oauthSignatureMethod = "HMAC-SHA1";
$oauthVersion = "1.0";

$sigBase = "GET&" . rawurlencode($requestTokenUrl) . "&"
    . rawurlencode("oauth_consumer_key=" . rawurlencode($consumerKey)
    . "&oauth_nonce=" . rawurlencode($nonce)
    . "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
    . "&oauth_timestamp=" . $oauthTimestamp
    . "&oauth_version=" . $oauthVersion);
Copy after login
Copy after login

$accessTokenUrl is the next endpoint obtained from the Details page. Generate new $oauthTimestamp and $nonce and send back $oauthVerifier from the Twitter authorization page. Not listed, but in the $_SESSION array, are the request credentials from the previous step, which are also required. This step in the authorization process requires another signature request. Once the signature is built, it will be used with the access credential request.

<?php
$sigKey = $consumerSecret . "&";
$oauthSig = base64_encode(hash_hmac("sha1", $sigBase, $sigKey, true));
Copy after login
Copy after login

This time $response contains very useful screen_name, user_id and long-awaited access credentials!

Summary

This article ends the authorization section. So far, you have learned how to create a new Twitter application and step through the OAuth "Dance" with the provided consumer credentials to get access credentials. In the second and final part of this series, I will discuss how to use access credentials to post tweets to a user's Twitter stream.

(The original picture should be retained here, but since the picture cannot be displayed directly, the picture link is retained)

OAuth 1.0 FAQ (FAQ)

(The original FAQ content should be retained here, but due to the length of the article, the FAQ part is omitted here for the sake of simplicity.)

The above is the detailed content of PHP Master | Understanding OAuth - Tweeting from Scratch, Part 1. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template