Kloudless Walkthrough: Building with our Open-Source Authenticator JS Library

This post was written by our engineer Chris Prochnow.

In this walkthrough, we’ll use the Kloudless open-source Authenticator JS library that prompts the user to grant access to a cloud service. We will look at the set-up of a basic web server, and explore how to use the Authenticator to set up a client-side form with all the data needed to send to the server-side for API requests.

We’ve written Authenticator.JS documentation that we will reference through the article. You can find it on GitHub here.

Getting started

Here is a form with all the fields needed to create a basic text file, which will eventually be stored in the Google Drive account that the user has been granted permission to access.

html


<form action="/post" method="post">
  <span>
    <input type="text" name="fileName" placeholder="File Name">
  </span>
  <span>
    <textarea name="fileBody&quot; rows="7">File text here.</textarea>
  </span>
  <span>
    <button type="submit">Create and upload file</button>
  </span>
  <input type="hidden" name="access_token" id="access_token" value="">
  <input type="hidden" name="account_id" id="account_id" value="">
</form>

Our web server is based on Node and Express. We will use the submitted form data to create a file, verify the authentication token, construct an API call, and run some cleanup once the action is complete. If you look at the code above, there are two inputs with the type=“hidden” that do not yet contain values. The values account_id and access_token must be supplied to us in order to access the storage service. Here is where the Authenticator JS library comes in.

First, we must obtain the correct values. To do so, we’ll need to embed the Authenticator in the client-side page using this script tag, which is documented in the Authenticator’s README here.

html

form2

This exposes a global Kloudless object, which contains the  Kloudless.authenticator method. This method is what we’ll use to trigger an authentication pop-up for the end-user:

Kloudless.authenticator(element, params, callback)

Before that can happen, we need to set up some logic to handle the end-user’s input: 

  • element is the triggering action. For this example, I’ve used jQuery to set the triggering element.
  • We also need to pass the configuration to the Kloudless.authenticator method to suit our application needs. These are required parameters that the end-user does not need to be aware of, but that do need to be passed in to the authentication.
  • At the minimum, you must pass the Kloudless application ID to identify the Kloudless app. This is provided as the client_id.

In our case, we only need to authenticate one service, Google Drive, so we will also be setting the scope to 'gdrive' in our configuration. The config will look like this:

  const config = {
      'client_id': ‘[YOUR CLIENT ID HERE]’,
      scope: 'gdrive',
  };

This gives a great setup for the authenticator.js!

Let’s see how what we have so far could be laid out:

$(document).ready(() => {
  const config = {
      'client_id': ‘[YOUR CLIENT ID HERE]’,
      ‘scope’: 'gdrive',
  };
  let auth = Kloudless.authenticator(press, config, callback);
});

Pairing data with input sources

The next pieces we need to include will be adding additional JS to set our received data to the correct inputs in our form, and setting a callback function that will determine what we do with the response data. The JS setup is pretty quick and involves defining some variables required using jQuery.

const $press = $('#submitAuth');
const $account_id = $('#account_id');
const $access_token = $('#access_token');
const $uploadButton = $('#uploadButton');

Callback function

Now for the callback function setup. We’ll need to handle errors, as well as decide what we’ll do with our successful data. Using the variables we just set up, we can reset the input values with the returned information:

let callback = function (result) {
   if (result.error) {
     console.log('An error occurred:', result.error);
     return;
   }   

    $account_id.val(result.account.id);
   $access_token.val(result.access_token);
   $uploadButton.prop('disabled',false);
 };

Our authenticator.js should now look something like this:

$(document).ready(() => {

 const config = {
     'client_id': 'NyRVsMqKtYS7g9t40WuSqhJCAxi4ANZ3p6MOsKfCFjXX_xcb',
     'scope': 'gdrive',
 };

 const $press = $('#submitAuth');
 const $account_id = $('#account_id');
 const $access_token = $('#access_token');
 const $uploadButton = $('#uploadButton');

 let callback = function (result) {
    if (result.error) {
      console.log('An error occurred:', result.error);
      return;
    }

    $account_id.val(result.account.id);
    $access_token.val(result.access_token);
    $uploadButton.prop('disabled',false);

  };

  let auth = Kloudless.authenticator($press, config, callback);

});

With that, we now have all the data needed to send to our server-side code to make an API call. This initial set-up uses an OAuth Kloudless key, which will be sufficient for basic development needs, but will be subject to rate-limit restrictions.


Setting up your own OAuth credentials

The next part of this blog will discuss how you can set up your own OAuth credentials. We’ll continue to use Google Drive as our example. 

Setting up these credentials provides several benefits: it allows you to manage your own tokens, implement a better branding experience, and exempt you from sharing the rate limits/quotas that Kloudless default keys are subject to. So let’s dive in!

To start off, navigate to the OAuth Credentials page in the developer portal for your app. You can find this page under Security -> Credentials in the developer portal. Be sure to select the correct app from the dropdown menu in the top left corner of the page.

You should see a list of cloud storage services that looks something like this:

credentials1.png

In our example, we are looking for the listing for Google Drive. When you find that entry, you will see that Google Drive is by default set to the Default Kloudless keys.

If you have existing accounts connected to the Default key, you will see a message denoting the number of accounts using that key, and an option to delete these accounts bordered in red, with some additional information.

credentials2.png

We do not need these accounts to continue to have access, and would like to have them re-authenticate through our app in the future. In this case I will check the box to have the existing accounts deleted.

Please note: this deletion does not affect the contents of your account or delete the account, but they do remove access to the account the keys are associated with.

Once you click ‘Save’, the first thing you’ll see is several new fields with instructions and helpful information specific to OAuth tokens and Google.

credential3.png

Keep this browser tab open—we’ll be coming back to it in a bit.

We’re now ready to head over to the Google Developers Console!

If you haven’t yet, create a new Google project. This is where you’ll manage apps and services that request access to your users’ Google accounts, and generate a Client ID/Consumer Key and our Client Secret/Consumer Secret.

Once that is done, there are a few steps to follow to get the information from the Google project. It should look something like the image below once you have created the project, with your project name in place of ‘kloudless test auth’:

credentials4.png

Our next step is to create the credentials needed for the Kloudless app. Click on the ‘Credentials’ tab to look at our options for creating credentials. In this case, we’re creating an OAuth Client ID, so select that option and then select the correct application type. In this case, I selected ‘Web application’.

All right! We now have a Client ID/Consumer Key and our Client Secret/Consumer Secret.

We’ve got something else to edit in the Google Developers Console: the callback URL or Redirect URL. Refer back to the Kloudless Credentials page and grab the link supplied there. Copy and paste that into the field under ‘authorized redirect URIs’, and click save.

credentials5.png

Note: keep in mind that the Client secret is just that—a SECRET. Be mindful of where you save it, and do not leave it exposed in your documentation.

Finally, head back to the Kloudless Credentials page. Enter the Client ID and Client secret into their respective fields, and save the app.

That’s it—you’ve successfully moved your app from using the default Kloudless OAuth keys to your own OAuth keys! 😀🎉


Conclusion

We hope that you found our introduction to the Kloudless Authenticator JS library useful. As we grow, we’ll be expanding our open-source initiatives—and the accompanying guides, walkthroughs, and other materials—so stay tuned for more posts like this one.

Want to build on these initiatives? Come join us—we’re hiring across a ton of different functions in our Berkeley, CA and Taipei, TW offices!

What're your thoughts!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s