Welcome folks today in this blog post we will be building a google oauth2 user login and logout
system in browser using the access token
in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to first of all see the directory structure of this web app. In this we will have three files namely index.html
,script.js and profile.html
as shown below
As you can see in the figure above we need to create the index.html
file which will contain the simple user login
button for the authentication as shown below
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>OAuth2 Flow</title> </head> <body> <button onclick="signIn()">Sign In With Google</button> </body> <script src="script.js"></script> </html> |
As you can see we have just the simple html5 button
out there inside the html and then we are attaching the onclick
event listener to it. When we click the button the signIn()
function will execute. We will define that function inside the custom javascript file called script.js
which we are including at the bottom. Now if you open the index.html
file inside the browser you will see the below result
Now guys we will be creating the script.js
file which will contain the javascript
code as shown below
script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
function signIn(){ // Google's OAuth 2.0 endpoint for requesting an access token var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth'; // Create <form> element to submit parameters to OAuth 2.0 endpoint. var form = document.createElement('form'); form.setAttribute('method', 'GET'); // Send as a GET request. form.setAttribute('action', oauth2Endpoint); // Parameters to pass to OAuth 2.0 endpoint. var params = {'client_id': '##yourclientid##', 'redirect_uri': '##yourredirecturi##', 'response_type': 'token', 'scope':'https://www.googleapis.com/auth/userinfo.profile', 'include_granted_scopes': 'true', 'state': 'pass-through value'}; // Add form parameters as hidden input values. for (var p in params) { var input = document.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', p); input.setAttribute('value', params[p]); form.appendChild(input); } // Add form to page and submit it to open the OAuth 2.0 endpoint. document.body.appendChild(form); form.submit(); } |
As you can see inside this javascript code
we are defining the function calledsignIn()
which will execute after we click the button. Inside this we are first of all defining the oauth2
user authentication endpoint where we will make a simple GET request using the fetch api inside the browser. Here we are constructing the object which contains some important information about your project. Here you need to copy paste your clientid and redirect url. So you can create these things in the steps that are shown below
Creating Client ID & Redirect URI
Now guys first of all go to google cloud console
and then create a new brand new project and then create the client id
credentials as shown below
And then we need to enter the javascript origin
and the redirect_url
for your respective project. This totally depends on your path of the project. Generally you will enter the homepage inside the javascript origin and the redirect url will be the actual file which we will redirect the user after successful authentication and display the profile page.
Now click on the save
button and your client_id and client_secret
will get created as shown below
Just copy paste your own client_id and replace it in the above code to make the app working. Now after adding the profile.html
file inside the redirect_url we also need to create that file also and copy paste the below code
profile.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Welcome to Profile Page</h1> <h2 id="name">Your Full Name is:</h2> <img id="image"/> <button onclick="logout()">Logout</button> </body> function logout(){ } </html> |
As you can see there will be a simple user profile page which contains the placeholder text for the name of the person and the profile picture as well. And then we have the button which allows user to logout from the app. When we click the logout button the function called logout()
function will get executed.
Getting the Access Token in OAuth2 Flow
Now guys we will look on how to get the access token from the get request that we will make. Now if you open the index.html
file inside the browser and click the sign in
button you will see the below result
You will be asked to select your respective google account and then after that the access_token will be created in the url of the browser itself as shown below
After getting the access token inside the url of the browser as a url params we need to parse it and store it inside the localstorage so that it stays after we refresh the page. Now you need to add some other code as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Welcome to Profile Page</h1> <h2 id="name">Your Full Name is:</h2> <img id="image"/> <button onclick="logout()">Logout</button> </body> <script> // Parse query string to see if page request is coming from OAuth 2.0 server. var params = {}; var regex = /([^&=]+)=([^&]*)/g, m; while (m = regex.exec(location.href)) { params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } if (Object.keys(params).length > 0) { localStorage.setItem('authInfo', JSON.stringify(params)); } window.history.pushState({}, document.title, "/" + "profile.html"); let info = JSON.parse(localStorage.getItem('authInfo')) console.log(info['access_token']) console.log(info['expires_in']) </script> |
As you can see we are using regular expressions and with the help of that we are storing the whole object inside localstorage. And then we are getting the access token and the expiry date of token displayed inside the console as shown below. And lastly we are removing the urlparams from the url using the pushState()
method. You will see the below result
After getting the accessToken it’s very easily to call any google api
and service because you are authenticated with the approved scopes. Here we have the profile and the email scope that we passed in the early step. And in the same profile.html
file you need to write the below javascript code as shown below
1 2 3 4 5 6 7 8 9 10 11 |
fetch("https://www.googleapis.com/oauth2/v3/userinfo", { headers: { "Authorization": `Bearer ${info['access_token']}` } }) .then(data => data.json()) .then((info) => { console.log(info) document.getElementById('name').innerHTML += info.name document.getElementById('image').setAttribute('src',info.picture) }) |
As you can see we are making a simple POST Request to the simple OAuth2 userinfo endpoint. And then we are also passing the header as well. And then we are getting the object of the logged in user which contains the email,profile
and profile picture.
Now we will be writing the logout()
function guys when we click the logout()
function inside this we will be revoking the access
to the oauth2 token. For this we need to make a simple POST Request to the endpoint as shown below
1 2 3 4 5 6 7 8 9 10 11 12 |
function logout() { fetch("https://oauth2.googleapis.com/revoke?token=" + info['access_token'], { method: 'POST', headers: { "Content-type": "application/x-www-form-urlencoded" } }) .then((data) => { location.href = "http://localhost:5500/index.html" }) } |
As you can see after the user has been successfully deleted. After logging the user out we will also redirect the user to the homepage.
FULL SOURCE CODE