Java Script Oauth2 Client Example

OAuth2 JavaScript Tutorial

When building modern and socially-aware web applications, the related problems of user authorization and authentication arise repeatedly. The rich API ecosystem offered by the Web to developers is to some extent complicated by questions of security: How do we make sure our users are who they say they are? How do we ensure they have authority to access a particular resource, like a profile or a photo album?

OAuth2 is an authorization protocol that solves these problems, enabling secure access to third-party APIs (like Google Maps' or Twitter's) in your own applications. This tutorial discusses the use of OAuth2 in a small example application that will make use of a Google+ API.

The Running Example

Throughout this tutorial we will be referring to a tiny demo application called "Logonoff". The only things we can do with it are log in, look at some data, and log out, and it looks like this:

logonoff
The application makes use of a JavaScript library called hello.js that presents a unified API for interacting with a number of OAuth providers, such as Google, Facebook, Twitter, Github, and more. We chose to use hello.js because it is popular, versatile, and simple.

If you want to run Logonoff on your system, you can download the code and follow the instructions on Github.

Recommendation

If your company is hiring a JavaScript developer, check out this JavaScript test prepared by our professionals. It will allow you to identify the best talents very easily!

Setting Up an App with an OAuth Provider

OAuth2 works by allowing developers to register their applications with an OAuth provider.  The provider is the third party whose API we are interested in using in our own application.  OAuth2 has been designed issue a unique Client ID to developers for each of their applications.  Client IDs allow developers to specify exactly which requests for which third-party resources are to be used in their apps.

Although hello.js supports a number of OAuth providers, this tutorial only makes use of the Google+ API.  Setting up an OAuth provider is simple but perhaps a little tedious, so we will now outline the process for Google's OAuth service.

Configure Google Credentials For OAuth with our App

  1. Navigate to the Google Developer Console and select Credentials in the API Manager.
  2. Next, click Create Credentials and pick OAuth client ID in the drop down menu.
  3. Then add a name, an origin URI and a redirect URI for your application.
    • The origin is the URI from which your web app's requests are made to the OAuth provider, in this case http://localhost:5000.
    • The redirect URI is the location to which the OAuth provider will return its tokens, and here we have used http://localhost:5000/
  4. Save and take note of the Client ID, you'll need this later.

Enable One of Google's APIs

Google exposes many APIs for interacting with its services. Having OAuth set up isn't of much use unless we enable one or two of these APIs. For this application, we only need to enable the Google+ API, which can be found under Social APIs in the Overview section of the Developer Panel.

Configuring hello.js for OAuth APIs

In this section we get down to actually using OAuth2 with hello.js. We must first include hello.js in our HTML files and initialize the library with our Google Client ID. In the case of our demo, we do this like so:

                      <script src="static/hello.all.js"></script> <script>   hello.init({     google: "Client-ID-From-Google-Dev-Console"     // not real id   }); </script>                  

When hello.js makes its request to Google's OAuth service, it will pass along the Client ID we provided to the init function. Google will then respond at the redirect URI you provided. The hello.js library decodes the response to a Javascript object, here is what it looks
like:

                      {    state: "",    access_token: "not a real access token",    token_type: "Bearer",    expires_in: 3600,    client_id: "your client id",    network: "google",    display: "popup",    redirect_uri: "http://localhost:5000/",    scope: "basic",    expires: 1464148474.442  }                  

To actually log in and log out of Google from within our application, we include two buttons that call the appropriate hello.js methods:

                      ><button onclick="hello('google').login()">google</button> <button onclick="hello('google').logout()">logout</button>                  

When we click the button labelled google, a popup window will appear asking us to allow access to our Google account by this application. Here is what the window should look like:

t4g_oauth2_screen

Now that we can log in, we want to do something with our Google API.

Using Auth Event Handlers

After we have hello.js included and initialized, we can use it to access the Google+ API we enabled earlier. We bind handler functions to a number of auth events, for example, when we log in or log out of an application. In the following snippit, we bind a function to the auth.login event that will add a profile picture to the page. We also bind to the auth.logout event to remove the user info when the user logs out.

                      <script>      hello.on('auth.login', function (auth) {        // add a greeting and access the thumbnail and name from       // the authorized response        hello(auth.network).api('/me').then(function (resp) { 	var lab = document.createElement("div"); 	lab.id = "pic_and_greet"; 	lab.innerHTML = '<img src="' + resp.thumbnail + '" /> Hey ' + resp.name; 	document.body.appendChild(lab);       });     });      // remove the greeting when we log out      hello.on('auth.logout', function () {       var lab = document.getElementById("pic_and_greet");       if (lab != null) document.body.removeChild( lab );     });  </script>                  

Here we are using one of the unified APIs of hello.js, namely the /me API that exposes basic profile data. The call to .api('/me') creates a promise to which we pass a callback for processing the response object, which includes the account name and profile thumbnail as properties.

OAuth2 JavaScript Tutorial - Step by Step Guide with Demo and Source Code Click To Tweet

Conclusion

In this tiny example we have seen how to use OAuth to make use of third party APIs in our own applications. We have seen how to register and set up Google's OAuth2 support using the hello.js library. We could just as easily set up OAuth with Twitter or Github or one of the dozens of other popular web services. If you would like try this example out for yourself, check out the code from Github.

Colin O'Keefe is a freelance programmer and software creative based in Kansas City, MO.  You can check out what he's up to at https://github.com/asciiascetic


This programming tutorial is written by Tests4Geeks team. We build programming tests and the test maker tool to make your recruitment process easier and faster.

Like the article? Share it please!

It will REALLY help us to make more content here.

collinsnessittere40.blogspot.com

Source: https://tests4geeks.com/blog/oauth2-javascript-tutorial/

0 Response to "Java Script Oauth2 Client Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel