Skip to content

Instantly share code, notes, and snippets.

@caalberts
Last active September 18, 2018 01:09
Show Gist options
  • Save caalberts/4f00502a977ae7a78f45 to your computer and use it in GitHub Desktop.
Save caalberts/4f00502a977ae7a78f45 to your computer and use it in GitHub Desktop.
Create custom OAuth2 connection to third party identity providers using Auth0

Custom OAuth2 Connection with Auth0

Understanding Auth0 authentication

Before we start with creating a custom OAuth2 connection in Auth0, it's worth to spend some time understanding the OAuth2 authentication process in Auth0. An OAuth2 authentication process starts with the application requesting Auth0 for authentication and ends with either the browser or the application server having an access token to represent the user. The access token can then be used to call the third party API on behalf of the user.

Pop-up mode Auth0 popup mode

Redirect mode Auth0 redirect mode

In both authentication modes, the process begins with the browser directing to Auth0 for authentication via the Auth0 Lock (Step 1). Auth0 will then request an authentication to the third party provider, via the third party's Authorization URL (Step 2).

After verifying the user by asking the user to log in (Step 3), the third party will return a code to Auth0's Callback URL configured in the third party's application setting (Step 4). Upon receiving the code, Auth0 will now exchange it for an access_token by making a POST request to the third party's Token URL (Step 5) and receive the access_token at the Callback URL (Step 6).

Once Auth0 has the user's access_token, it would return a id_token corresponding to the user to the application. This is where the pop-up mode and redirect mode differ. In pop-up mode, the id_token will be sent to the browser by calling a callback function, which eventually saves the id_token in the browser's local storage (Step 7 of pop-up mode).

In redirect mode, another sequence of code and id_token exchange happens between Auth0 and the application server, where Auth0 sends a code to the application server (Step 7 of redirect mode). The application server now needs to exchange the code for the id_token (Step 8 and 9).

Setting up a custom OAuth2 connection in Auth0

  1. Create a new Auth0 application
  • Create a new Auth0 application in Auth0 dashboard
  • Take note of the following details:
    • Domain - Your Auth0 domain, which we'll refer to as YOUR_AUTH0_DOMAIN. This will be needed in step 2 when registering a third party application.
    • Client ID - Your Auth0 application ID. We'll refer to is as AUTH0_CLIENT_ID
    • Client Secret - Your Auth0 application Secret and will be referred to as AUTH0_CLIENT_SECRET
  • Enter your application URL in Allowed Callback URLs. Be sure to include both http://localhost and your production URL such as http://your-app.herokuapp.com
  1. Register a new developer application with third party
  • Go to the respective third party developer website and register an application
  • Take note of your application key/id and secret. For this exercise we'll refer to them as APPLICATION_KEY and APPLICATION_SECRET
  • Set your Auth0 domain https://YOUR_AUTH0_DOMAIN.auth0.com/login/callback as redirect URI
  • Go through the third party API documentation to find the authentication endpoints. You'll need the following:
    • authorization url (such as /oauth2/authorize) - This will be the url where the user will be redirected to in order to authorize your application. We'll refer to it as AUTHORIZATION_URL
    • token url (such as /oauth2/token) - This will be the url which Auth0 calls to exchange code for token. We'll call this TOKEN_URL
    • get account details url (such as /users/get_current_account) - Let's call it USER_DETAIL_URL

Checkpoint

By now, you should have the following ids/keys and secrets noted down and ideally saved as environment variables for later use:

  • AUTH0_CLIENT_ID
  • AUTH0_CLIENT_SECRET
  • APPLICATION_KEY
  • APPLICATION_SECRET

And the following URLs:

  • AUTHORIZATION_URL
  • TOKEN_URL
  • USER_DETAIL_URL
  1. Create a custom connection to third party with Auth0
  • Obtain an Auth0 APIv2 token with create:connections scope. Details can be found here
  • Create a file called custom-oauth2-connection.json with the following content:
    {
      "name": "custom-connection-oauth2",
      "strategy": "oauth2",
      "options": {
        // Your application key issued by third party
        "client_id": "{APPLICATION_KEY}",
        // Your application secret issued by third party
        "client_secret": "{APPLICATION_SECRET}",
        // Third party's authorization URL
        "authorizationURL": "{AUTHORIZATION_URL}",
        // Third party's token URL
        "tokenURL": "{TOKEN_URL}",
        "scripts": { // scripts to be executed after successful authentication
          "fetchUserProfile": "function(token, ctx, cb) {
            request.get('{USER_DETAIL_URL}', {
              headers: { 'Authorization': 'Bearer ' + token }
              }, function(e, r, b) {
                if (e) return cb(e);
                if (r.statusCode !== 200 ) return cb(new Error('StatusCode: ' + r.statusCode));
                cb(null, JSON.parse(b));
              });
            }"
        }
      },
      "enabled_clients":["{AUTH0_CLIENT_ID}"] // Your Auth0 client ID
    }
    
  • Run the following command to create the custom connection in Auth0 curl -H "Content-Type: application/json" -H 'Authorization: Bearer {AUTH0_API_V2_TOKEN}' -d @custom-oauth2-connection.json https://YOUR_AUTH0_DOMAIN.auth0.com/api/v2/connections
  • Successful request will return the JSON object in custom-oauth2-connection.json and a new connection id

Checkpoint

At this point, you'd have your Auth0 client set up, third party application set up and a connection set up between Auth0 and the third party.

Using the custom OAuth2 connection

Now that the connection is set up, let's use it in an application to get a user token. There are 2 ways of using the custom connection, depending on where you need the user token.

  1. Pop-up mode In popup mode, the application will request an authentication to Auth0 and the end result will be that Auth0 provides a user token to the application which can then be saved in the browser's local storage. This method is suitable for use by a single page application to call the third party API directly on the browser. Sample code for popup mode

  2. Redirect mode The user token will be sent to the application server after a series of code and token exchanges between the application, Auth0 and the third party provider. This is suitable when you need the server to make API requests on behalf of the user. Sample code for redirect mode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment