images
16th July, 2019

OAuth 2.0 for Client-side Web

To retrieve Data or Resources of the user, we need to register as a client at the authorization server.

Provide details in order to access User resources in the authorization server.

  1. Application Name: Name of Application be shown to User 
  2. Redirect URLs: Authorization Code and Access Token are received through that URLs.
  3. Grant/Authorization Type: Access of Resources Type is controlled by it.
  4. Origins: Hostname allowed to request for resources via  XMLHttpRequest its Optionals.

 

Steps:

1. Add link to index.html 

<script src="https://apis.google.com/js/platform.js" async="" defer=""></script>

 

 
GoogleAuth.signIn();

and below link to a page where you want a Sign In/Up button. 

<button id="googleBtn">Button Name</button>

 

2. The script required to function an Oauth2.0 as below:

Declaration : 

var gapi, auth2;

 

Random strings are generated by the authorization server when the client requests them is known as Token. Example of  client_id  to access to user content is:  'xxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com'   as we use only one token to authenticate the client as previously OAuth1 used to use two for each API calls which is used to generate the signature.

Functions:

//initilization of OAuth
    function functionName() {
        gapi.load('auth2', () => {
            auth2 = gapi.auth2.init({
                client_id: 'xxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
                //client_id: provided by Authorization Serve
                scope: 'profile email'
                //Scope:ReadOnly Data/Resources you need from Resource Server
            });
            // Attach Event Handler to Button
            attachSignin(document.getElementById('googleBtn'));
        });
    }

Also,

function attachSignin(element) {
        auth2.attachClickHandler(element, {},
            (googleUser) => {   
                //googleUser, an object with TokenId
                let obj = { id_token: googleUser.getAuthResponse().id_token }
                //Send obj to server
            });
    }

 

Some of the OAuth use the client password may need a server, which must be kept in a secure place. This problem can be byPass by creating a back-end to do the OAuth server calls for Mobile and Desktop Apps.

Tags