adding google sign-in to your webapp – hello world


*Check out the video to see me follow along with the code.

Gotten stuck in a rabbit hole figuring out how to add “Log In with Google” to your web app? In this series, I’ll cover:

  • why you might want to use the Sign-In for Website JS library, and getting started with it
  • Adding the library via javascript
  • adding it to an existing project (angular & react)

Their docs give you a decent place to start if you know what you’re looking for, but there’s a few areas where their docs and other guides online can be confusing. There’s also minimal guidance as to how to use it within existing projects.

  • Am I supposed to be following the Google Identity docs or do I need Google Sign-in for Web??
  • Wait, why are those 2 guides so different? They even load different libraries!
  • This should be simple! I’m just trying to load a users avatar!!

The answer to “How do I add Log in with Google?” boils down to 1 question you need to be able to answer: What exactly are you trying to do?

  • Do you just want to be able to see the users name and picture, maybe their email? Use the Sign-In for Websites library (full walkthrough below).
  • Do you have your own user database and want to offer Google login as an extra option? This is Federated Login and you’d want to use their OpenID Connect protocol. This is used by platforms like auth0, firebase, oneidentity.
  • Do you want to be able to interact with the users Google account and do things like see their calendar, or create a Google doc? You’ll need to use their OAuth workflow.

For the purposes of this series, I’m going to explore when you should use the Sign-In for Websites library which uses the OpenID Connect protocol (also used by Federated Login systems) – this library can be easily misunderstood, but is still incredibly useful. The goal of this authentication library is to let you identify a user with their Google account. Thats it.

So when should I use it?

Good reasons to use it:
– you have some content stored on a backend service that you deliver via an API only after the user has signed in
– you only have to support Google/G-Suite users
– you dont need to authorize users (e.g. allow some users to be admins)
– your site is public
– you have a single-page app

Use cases where it’s worth considering federated login:
– you have pre-existing user content stored on a backend service
– you have an internal site that you want to restrict to users from a specific domain. (e.g. only users from @example.com should see it)
– you want to prevent people from seeing your page unless they’ve logged in. The best you can do with this library is show/hide elements on the page if the user logged in, but thats enough if you only load data from an API after a user has logged in.

The library is designed to be used with HTML/JS and only interacts with your page via the “Sign in with Google” button. You can integrate this with other frameworks like Angular/React which I’ll be covering in the next part of this series.

Adding Google Sign-in step-by-step

1. Hello World HTML

To start with, all you need is an index.html file.

<!DOCTYPE html>
<html>

<head>
  <title>Google Auth Demo</title>
</head>
<body>
  <h1>Welcome to the Demo</h1>
</body>
</html>

2. Add the Google Sign-In Button

Before adding in the button, you first need to create a client ID/secret which is a way of identifying that you, the developer, are allowing users to get the identity information from Google and delivered to your website.

Creating credentials for Sign-In

  • Go to the Google API Console – https://console.developers.google.com/apis/dashboard
  • Create a new project, or use an existing project if you already have one set up.
  • Then click on Credentials -> Create Credentials -> OAuth Client ID

Here’s what I put in for this demo:

Name: google-auth-demo
Authorized Javascript Origins: http://localhost:8080
Authorized Redirect URIs: empty

*A note about the Javascript origins: if you have a plain HTML file that you load in your browser using a file path like /home/dperez/index.html, this won’t work. You’ll need to “serve” your website on your computer so that you have a URL, even if its just localhost. You can use python -m SimpleHTTPServer 8080 (which is commonly available) to serve up your current directory or you can use an npm package like http-server.

You’ll then get a Client ID & Client Secret. These are 2 identifiers for your Oauth Client. At this point, you have authorized that Client ID to accept logins and return you the users information. Copy them down. If you accidentally click out of the screen, you can always copy them again later.

Add the library + credentials + button to your HTML

In your index.html page, add the following to your HTML page:

...
<head>
  ...
  <meta name="google-signin-client_id" content="your-client-id-goes-here">
  <script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
  <h1>Welcome to the Demo</h1>
  <div class="g-signin2"></div>
</body>

The script tag grabs the library from Google that reads your <meta> tag to use as the Client ID, and then automatically re-styles the button with the CSS class .g-signin2.

At this point, if you refresh your page, you should see a pretty Sign-In button. If you click it, you’ll go through your Google Login flow in a popup, and you’ll finally land back on your site, and the button will say, “Signed In”.

Great, we’re most of the way there! But in its current form, this is still useless.

3. Identify the user

  1. Update the g-signin2 div to include the data-onsuccess attribute:
<div class="g-signin2" data-onsuccess="onSignIn"></div>

That attribute contains the name of the function that will be called once a user has successfully logged in with Google.

  1. Create a function called “onSignIn”.
<body>
  ...
  <script>
    function onSignIn(googleUser) {
      // get user profile information
      console.log(googleUser.getBasicProfile())
    }
  </script>
</body>

Your onSignIn function will be called with an argument containing the information provided by Google. If you refresh the page, you’ll notice that
1. You’re automatically signed in
2. The button gets updated very shortly after refresh (1s delay)

If you open up your javascript console, you’ll see the users information printed:

{
  Eea: "108716981921401766503"
  Paa: "https://lh3.googleusercontent.com/-y_ba58pC4us/AAAAAAAAAAI/AAAAAAAAAYE/wMGKOxlWR90/s96-c/photo.jpg"
  U3: "perez.dp@gmail.com"
  ig: "danny perez"
  ofa: "danny"
  wea: "perez"
}

This is the basic profile containing a series of values that identify me as a user. Under any normal circumstances, this object would have fields like name or email, but for some unknown reason (I wish I had the answer but they havent given an answer either), its gibberish – but at least its consistent and hasn’t changed.

You can either get the data directly by doing googleUser.getBasicProfile()['U3'] or use the more human-readable approach by using the functions like googleUser.getBasicProfile().getName() or googleUser.getBasicProfile().getEmail(). (See here for the javascript client api reference docs)

4. Sign out

Add a sign out button after the user has signed in by adding a button in your index.html and the click handler in your javascript.

index.html

<body>
...
  <button onclick="signOut()">Sign out</button>
</body>
function signOut() {
  gapi.auth2.getAuthInstance().signOut().then(function() {
    console.log('user signed out')
  })
}

Great! At this point, we’ve added a Sign-In with Google button and we can identify the user by name/email. Also, thats it. Thats all this library can help you do.

…but what about basic things like saving users data to the backend? or showing an admin page?! Why isn’t this in the docs?! That’ll be covered on the next post coming 7/22 – using the js library to add it to your site without HTML.

Update: Here’s the link for part 2 of the series – Using the js library

You might also like

More Similar Posts

Menu