How to Authenticate Users With Twitter OAuth 2.0 | Envato Tuts+ (2024)

How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (1)

Anton Bagaiev

6 min read

English
  • English
  • Español

Coding Fundamentals Rest API PHP

In this tutorial, youwill learn how to use Twitter API 1.1 and OAuth 2.0 to authenticate users of your application and publish atest tweet.

Why Do We Need an Authentication Framework?

To create services which act onbehalf of users' accounts and make it really secure and easy todevelop, we need three things:

  • Twitter application
  • REST API
  • access to theuser account

To put the pieces together into a working mechanism, we need an authentication framework.As a Twitter standard, the REST APIidentifies Twitter applications and users using OAuth.

What Is OAuth?

According tooauth.net, OAuth is:

An open protocol to allow secureauthorization in a simple and standard method from web, mobile anddesktop applications.

OAuth is the most common authorization framework today, and it is used on most common web applications and services, like GitHub, Google, Facebook, and, of course, Twitter.

This framework allows users togrant you permissionto act on their behalf without sharing the accountpassword. After the user hasgiven permission, OAuth will return you a token. Thistoken itself grants access to make requests on behalf of the user.

Tokens from Twitterdo not have an expiration time, but they can become invalid after the user hasrejected your application. Also, theTwitter crew can suspend your application if you are exceeding limits orperforming other actions that violate theAPI Terms. You canreview these terms to find out more about specific violations.

Create Your Application

As a first step, we need to set up a newTwitter application. Let's create a new application on theapplicationmanagement page.

How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (2)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (3)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (4)

After logging in, you need to click the Create New Appbutton and fill intheform with your application details:name, description, website and callback URL.

What is the callback URL? Whenusers accept our application to use theiraccount, the browser will deliver them to this URL with the OAuth verifier in GET. And we will use this verifier to get the user access token.

How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (5)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (6)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (7)

Notice:Don't forget to replace the websiteand callback URL with your public domain when you share yourapplication with real users.

After filling in the form, you can sign the Developer Agreement and click the Submit button to create yourapplication.

How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (8)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (9)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (10)

Congratulations! Now you have access to a page where you canlook at thedetails and edit settings of your new application,change permissions and manage keys and access tokens. Navigate to the Keys and Access Tokenstab and find theConsumer KeyandConsumer Secret.Wewill be using themshortly.

Start Coding

Choosing a Library

Before starting to code, we need tochoose alibrary to work with Twitter API and Oauth 2.0. You can get anoverview of theexisting libraries on the Twitter developers page. In thistutorial I will use TwitterOAuth as the most popular and easy to use. Wecan install it from the command line with Composer:

1
composer require abraham/twitteroauth

The Config File

Let's create a new file named config.php to store all static data. Specify the followingdetails in your application.

1
<?php
2
3
return [
4
 //
5
 'consumer_key' => 'EPKXCv3tUsq9DoxwZy616Cy1o',
6
 'consumer_secret' => 'UXnAeXkCZFIOnLVQCS4LFR7GsCTrOiU77OGSFL3dUoYZiTxU8x',
7
8
 //
9
 'url_login' => 'http://localhost/twitter_login.php',
10
 'url_callback' => 'http://localhost/twitter_callback.php',
11
];

Start the Login Script

Now create a new file named twitter_login.php and include Composer autoload, TwitterOAuth library, start session, and import the settings of our applicationfrom the config file.

1
<?php
2
3
require_once 'vendor/autoload.php';
4
use Abraham\TwitterOAuth\TwitterOAuth;
5
6
session_start();
7
8
$config = require_once 'config.php';

Request Auth

In this part we need to request the user to authorize our application. To reach this goal we will create an object of the TwitterOAuth class, request a token of the application from the Twitter API, get the URL of the authorize page using this token, and redirect the user to this page.

1
// create TwitterOAuth object
2
$twitteroauth = new TwitterOAuth($config['consumer_key'], $config['consumer_secret']);
3
4
// request token of application
5
$request_token = $twitteroauth->oauth(
6
 'oauth/request_token', [
7
 'oauth_callback' => $config['url_callback']
8
 ]
9
);
10
11
// throw exception if something gone wrong
12
if($twitteroauth->getLastHttpCode() != 200) {
13
 throw new \Exception('There was a problem performing this request');
14
}
15
16
// save token of application to session
17
$_SESSION['oauth_token'] = $request_token['oauth_token'];
18
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
19
20
// generate the URL to make request to authorize our application
21
$url = $twitteroauth->url(
22
 'oauth/authorize', [
23
 'oauth_token' => $request_token['oauth_token']
24
 ]
25
);
26
27
// and redirect
28
header('Location: '. $url);

Make a note that we are saving application tokens to the session, because we will need them in the next step.

Now you can run this script in the browser, andifeverything goes well, you will be redirected to the Twitter API page withsomething like this:

How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (11)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (12)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (13)

You will be redirected to the callback URL by clicking the Authorize appbutton. But not sofast—first we need to create a callback script.

Get the User Token

Our next step is to create a callback script. Let's create a new file namedtwitter_callback.phpand include the TwitterOAuth library, config file, and start session as we did in the previous part.

Then we will check if we received an auth verifier parameter from the Twitter API. Ifsomething is missing, we will redirect the userto log in again.

1
$oauth_verifier = filter_input(INPUT_GET, 'oauth_verifier');
2
3
if (empty($oauth_verifier) ||
4
 empty($_SESSION['oauth_token']) ||
5
 empty($_SESSION['oauth_token_secret'])
6
) {
7
 // something's missing, go and login again
8
 header('Location: ' . $config['url_login']);
9
}

The next step is to connect to the Twitter API with the application token and request a user token using the OAuth verifier:

1
// connect with application token
2
$connection = new TwitterOAuth(
3
 $config['consumer_key'],
4
 $config['consumer_secret'],
5
 $_SESSION['oauth_token'],
6
 $_SESSION['oauth_token_secret']
7
);
8
9
// request user token
10
$token = $connection->oauth(
11
 'oauth/access_token', [
12
 'oauth_verifier' => $oauth_verifier
13
 ]
14
);

And now you've got the user token stored in the$token variable.

How to Use This Token

We can use this token toact on behalf of theuser's account. We can store it in the session or save in the database to manage theuser account next time without requesting permission. To connect to the Twitter API with the user token, you just need to do this:

1
$twitter = new TwitterOAuth(
2
 $config['consumer_key'],
3
 $config['consumer_secret'],
4
 $token['oauth_token'],
5
 $token['oauth_token_secret']
6
);

Create a Test Tweet

To create anew tweet from the user's account, we need to add just a little piece of code:

1
$status = $twitter->post(
2
 "statuses/update", [
3
 "status" => "Thank you @nedavayruby, now I know how to authenticate users with Twitter because of this tutorial https://goo.gl/N2Znbb"
4
 ]
5
);
6
7
echo ('Created new status with #' . $status->id . PHP_EOL);

Also you can get details of the status from the answer of the API stored in the$status variable.

Finally, we are ready to test our script.

How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (14)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (15)How to Authenticate Users With Twitter OAuth2.0 | Envato Tuts+ (16)

Conclusion

As you can see, creating a Twitterapplication is not so hard. Now you have all the API features to use: youcan create new tweets, upload media, manage friendships and so on.

Keep in mind that now you can collectOAuth tokens and you have great power to act on behalf of your users.But with great power comes great responsibility—that's whyyou need tohandle this situation gracefully and serve a quality user experience.

If you have questions or feedback, feelfree to post them in the comments section. I'll be looking forwardto it and willtry to answer each of your comments.

Further Reading and Related Links

Note that I've prepared a full project for this tutorial on GitHub, and you can take a look at it with a link on the right side of the site or using this link.

How to Authenticate Users With Twitter OAuth 2.0 | Envato Tuts+ (2024)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Lidia Grady

Last Updated:

Views: 5435

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.