The Daraja HTTP Framework contains an example for a web application which uses OAuth 2.0 authorization to access the GitHub REST API. (This is an update of a post from 2019)

Requirements

  • Daraja HTTP Framework.
  • A GitHub developer account.
  • Lazarus 2.x or Delphi 2009+.
  • Current version of Indy and matching OpenSSL DLLs.
  • For Delphi, the JsonDataObject library is required.
  • For Lazarus, the built-in JSON library is used.

What it does

After authorizing the GitHub OAuth application, the example sends a request to the GitHub user API to read your GitHub user profile information.

authorize

Expected output

First step: GitHub OAuth App configuration

You need to configure a OAuth App in the GitHub developer settings screen. If you created it, copy the Client ID and the Client Secret to the source file GitHubHelper.pas.

Callback URL

In the GitHub developer settings screen, configure the callback URL http://localhost/oauth2callback. The GitHub authorization flow will send a redirect to this URL.

Second step: source code configuration

Insert the client id and the client secret in unit GitHubHelper:

Note: your client_id value will be different from the value 'e7150...42799' shown above.

Next step: start the program

What it does

  1. the program starts the local web server on localhost
  2. the program launches your web browser and navigates to http://localhost/index.html
  3. the start page redirects to the GitHub server which asks to log in and give permission to access user data
  4. after the user signed in, the code sends a request to the GitHub API and displays the result

Authorization screen

The example program requests read-only access to the user profile by specifying only the scopes read:user and read:email:

  • read:user grants access to read a user’s profile data.
  • user:email grants read access to a user’s email addresses

For more details about scopes, see https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/

With these scopes, the authorization prompt indicates that the app requests read access to your private profile information:

authorize

Final step: program fetches user data

When the authorization was successful, GitHub redirects the to the callback URL (in this example, it is http://localhost/oauth2callback but in a production system, it could be https://example.com/oauth2callback). The program can read the OAuth 2.0 token, and used it to request data from GitHub. Finally, the browser displays the GitHub server response.

Note: OpenSSL DLLs are required

The program sends a HTTP GET request to https://api.github.com/user to read your user profile information. If you see this error message, check if the matching versions of OpenDDL DLLs are in the application folder.

Security note

After testing, you should revoke the user tokens. To do so, go to the OAuth App settings screen and click on “Revoke all user tokens”.


dj

Leave a comment