At this point, you’ve built the application registration screen, you’re ready to let the developer register the application. When the developer registers the application, you’ll need to generate a client ID and optionally a secret. When generating these strings, there are some important things to consider in terms of security and aesthetics.
The clientsecret is a secret known only to the application and the authorization server. It must be sufficiently random to not be guessable, which means you should avoid using common UUID libraries which often take into account the timestamp or MAC address of the server generating it. Copy the consumer key (API key) and consumer secret from the screen into your application; Create Your Access Token for OAuth. After creating your Twitter Application, you have to give the access to your Twitter Account to use this Application. To do this, click the Create my Access Token.
Register The Generated Consumer Key And Consumer Secrets
Client ID
The
client_id
is a public identifier for apps. Even though it’s public, it’s best that it isn’t guessable by third parties, so many implementations use something like a 32-character hex string. It must also be unique across all clients that the authorization server handles. If the client ID is guessable, it makes it slightly easier to craft phishing attacks against arbitrary applications.Here are some examples of client IDs from services that support OAuth 2.0:
- Foursquare:
ZYDPLLBWSK3MVQJSIYHB1OR2JXCY0X2C5UJ2QAR2MAAIT5Q
- Github:
6779ef20e75817b79602
- Google:
292085223830.apps.googleusercontent.com
- Instagram:
f2a1ed52710d4533bde25be6da03b6e3
- SoundCloud:
269d98e4922fb3895e9ae2108cbb5064
- Windows Live:
00000000400ECB04
If the developer is creating a “public” app (a mobile or single-page app), then you should not issue a
client_secret
to the app at all. This is the only way to ensure the developer won’t accidentally include it in their application. If it doesn’t exist, it can’t be leaked!Because of this, you should ask the developer what type of application they are creating when they start. You can present the following options to them, and only issue a secret for “web server” apps.
- Web-server app
- Single-page app
- Native app
- Mobile app
Of course there’s nothing stopping the developer from choosing the wrong option, but by taking the initiative of asking the developer what kind of app the credentials will be used by, you can help reduce the likelihood of leaked secrets.
Client Secret
The
client_secret
is a secret known only to the application and the authorization server. It must be sufficiently random to not be guessable, which means you should avoid using common UUID libraries which often take into account the timestamp or MAC address of the server generating it. A great way to generate a secure secret is to use a cryptographically-secure library to generate a 256-bit value and converting it to a hexadecimal representation.In PHP, you can use an OpenSSL function to generate random bytes and convert to a hex string:
Or in PHP 7 and above, the built-in function
random_bytes
can be used.In Ruby, you can use the SecureRandom library to generate a hex string:
It is critical that developers never include their
client_secret
in public (mobile or browser-based) apps. To help developers avoid accidentally doing this, it’s best to make the client secret visually different from the ID. This way when developers copy and paste the ID and secret, it is easy to recognize which is which. Usually using a longer string for the secret is a good way to indicate this, or prefixing the secret with “secret” or “private”.Storing and Displaying the Client ID and Secret
For each registered application, you’ll need to store the public
client_id
and the private client_secret
. Because these are essentially equivalent to a username and password, you should not store the secret in plain text, instead only store an encrypted or hashed version, to help reduce the likelihood of the secret leaking.When you issue the client ID and secret, you will need to display them to the developer. Most services provide a way for developers to retrieve the secret of an existing application, although some will only display the secret one time and require the developer store it themselves immediately. If you display the secret only one time, you can store a hashed version of it to avoid storing the plaintext secret at all.
If you store the secret in a way that can be displayed later to developers, you should take extra precautions when revealing the secret. A common way to protect the secret is to insert a “re-authorization” prompt when the developer attempts to retrieve the secret.
The service asks the developer to confirm their password before it will reveal the secret. This is commonly seen in Amazon or GitHub’s websites when you attempt to view or update sensitive information.
Additionally, obscuring the secret on the application detail page until the developer clicks “show” is a good way to prevent accidental leakage of the secret.
If you’ve ever integrated with another API that requires security (such as Twitter), you’ve probably consumed an OAuth service. In this article, I’ll explore what it takes to create your own three-legged OAuth server allowing you, for example, to create your own secure API which you can release publicly.
When dealing with OAuth, you will typically see it implemented as a two-legged or three-legged OAuth server. The major difference between them is that two-legged authentication doesn’t involve another user. For example, if you want to access a specific user’s Twitter information, you would consume the three-legged server because an access token must be generated for the user in your application, versus just Twitter providing you a token. We’ll focus on the three-legged variety since it’s more practical for real-world use.
We’ll use oauth-php to perform a lot of the heavy lifting for us. The library is hosted on Google Code and is not listed in Packagist, but it can still be installed using Composer. For details, check out the composer.json file in code that accompanies this article available on GitHub.
Understanding the Flow
When using a three-legged OAuth server, the typical flow that a developer would take to implement and consume the service is as follows: Bitlocker recovery key generator.
The above image, courtesy of OAuth.net, is quite complex, but in simple terms it shows the following:
- The consumer requests a token from the server
- The consumer then directs the user to a login page, passing the token with them
- The user logs in and is redirected back to the consumer with an access token
- The consumer takes the access token and requests the OAuth token to use with future secure requests
- The OAuth token is retrieved, and the developer can now make secure requests by passing the token for validation
Setting up the Database
With the oauth-php library in an accessible location, a new database needs to be created and initialized. I’ll be using the schema script found in
library/store/mysql/mysql.sql
.Oauth Consumer Key
If you browse through the tables, you’ll see that the
oauth_server_registry
table contains a field called osr_usa_id_ref
. This is populated during the registration process by the OAuth server. It assumes you have an already existing users table that it will be related to. If you do, that’s perfect! But if not, then here is some basic SQL to create a standard user table:Creating the OAuth Server
Let’s start writing the OAuth server. The following is common to the rest of our code, so I’ve placed it in the separate file
include/common.php
:The file adds an additional HTTP header to each request to inform clients that this is an OAuth server. Notice that it references
services.xrds.php
; this file is provided with the example that comes with the oauth-php library. You should copy it from example/server/www/services.xrds.php
to the root public directory of the web server.The next few lines of code establish a connection to the database (the connection information should be updated accordingly to your own set up) and creates new instances of
OAuthStore
and OAuthServer
objects provided by the library.The set up for the OAuth server is now complete and the server is ready to be fully implemented. In the remaining examples, the
includes/common.php
file must be included each time to instantiate the server.Allowing Registration
Before developers can consume your OAuth server, they must register themselves with it. To allow this, we need to create a basic registration form. The following fields are required because they are passed to the library:
requester_name
and requester_email
. The remaining fields are optional: application_uri
and callback_uri
.As I mentioned earlier, the library assumes you have existing users who want to consume your server. In the following code, I create a new user in the
users
table, then retrieve the ID, and then pass it to the updateConsumer()
method creating (or updating) the consumer key and secret for this user. When you integrate this into your application, this piece should be modified and placed under your existing login process where you already know who the user is who is registering for access.On completion of the registration, the user’s new consumer key and consumer secret key are outputted. These values should be saved by the user for future use.
Now that a user is registered, they can begin making requests for an access token!
Generating a Request Token
Once a user has registered, they should perform an OAuth request to your
request_token.php
file. This file (once again because of the library) is extremely simple:The
requestToken()
method takes care of validating that the user has provided a valid consumer key and signature. If the request is valid, a new request token is returned.Exchanging the Request Token for an Access Token
The user should be redirected to your login page once a request token has been generated. This page should expect the following URL parameters:
oauth_token
and oauth_callback
.The login page should retrieve the user from the users table. Once retrieved, the user ID is passed (along with the
The necessary logic of a basic
oauth_token
) to the authorizeVerify()
method provided by the library. Assuming the user has authorized the application, the ID of the logged in user is then associated with the consumer’s key allowing them secure access to this user’s data.The necessary logic of a basic
login.php
might look like the following:After the user logs in, they will be redirected back to the consuming developer’s website (via the
oauth_callback
parameter) with a valid token. This token and verify key can then be used in the exchange for a valid access token.A basic
access_token.php
file looks like this:This file is as simple as the previously created
request_token.php
. The work is all done inside the accessToken()
method provided by the oauth-php library. Upon a successful request, a valid oauth_token
and oauth_token_secret
are outputted that should be stored and used with future requests to your API.Validating a Request
At this point, the OAuth server is up and running. But we still need to verify that a request contains a valid OAuth signature. I’ve created a basic test file that does just that:
![Consumer Consumer](/uploads/1/2/6/5/126522540/858805049.png)
In the example, if the request is verified, I simply echo the user id of the user who logged in. I would suggest creating a re-usable method that contains this code for any API calls that require security.
Testing the OAuth Server
Finally, it’s time to test the OAuth server. Below is a simple test file that performs the above steps to require a user to login and performs a secure request:
OAuth requires timestamps and signatures to be appended to each request, and once again this library will perform this for us.
The first part of the above code is configuration information that should be updated accordingly to match your needs. The user ID, consumer key, and consumer secret key are all generated during the registration process on the server.
As described during the introduction to a three-legged OAuth server, the following process is performed in the above test file:
- Ask for a request token (via the
request_token.php
file) with the consumer key - Upon receiving the token, redirect the user to the login page passing the token and callback URL via URL parameters
- Once the user is logged in, they are redirected back to the above test page. The test page takes the token and asks for an access token (via the
access_token.php
file) - Upon success, the necessary OAuth information is returned and the test file performs a secure request to
test_request.php
. - If all goes well a basic “Hello 1” will be displayed.
Summary
At this point, you should know how to create a basic OAuth server. Using the
test_request.php
file as example, you can begin creating more features that are secured with Oauth! If you’d like to play around with some code, full source code for this article is available on GitHub.Image via Fotolia
And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start PHP.
Comments on this article are closed. Have a question about PHP? Why not ask it on our forums?