Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Last active May 24, 2022 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatsuyasusukida/bec4108846bbe41961917e616efc0981 to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/bec4108846bbe41961917e616efc0981 to your computer and use it in GitHub Desktop.
🐥 How to sign in with Google account using Firebase Auth [video version available]

🐥 How to sign in with Google account using Firebase Auth [video version available]

Video thumbnail: How to sign in with Google account using Firebase Auth [video version available]

Abount this article

This article describes how to do the following 3 points using Firebase Auth.

  • Sign in with your Google account
  • Sign out
  • Get user ID

The related resources are shown below.

Workflow

The workflow is shown below.

  1. Creating a Firebase project
  2. Creating a Firebase app
  3. Enabling Authentication
  4. Coding preparation
  5. Coding
  6. Operation check

Creating a Firebase project

Access Firebase Web Console and click "Add project". The "Add project" screen will be displayed. Enter the project name (e.g. firebase-auth-google-(8-digit date)).

When the "Google Analytics" screen is displayed, uncheck "Enable Google Analytics for this project" and then click the "Create" button.

Click the "Continue" button when creating the project have finished.

The project overview page for the created project is displayed.

Creating a Firebase app

Click the "Web" button next to iOS or Android under "Get started by adding Firebase to your app".

"Add Firebase to your web app"

When the "Add Firebase to your web app" screen appears, enter your app's nickname (eg firebase-auth-google-(8-digit date)-app) and then click the "Register app" button. At this time, do not check "Also set up Firebase Hosting for this app".

When the registration of the application is completed, the sample code including firebaseConfig will be displayed, so copy the contents of firebaseConfig for later steps. It is convenient to use the copy button.

When you have copyed the contents of firebase Config, click the "x" button at the top left of the screen to close the "Add Firebase to your web app" screen.

Enabling Authentication

Click "Authentication" in the menu on the left side of the page to go to the Authentication page.

Activate Authentication by clicking the "Get started" button included on the Authentication page.

Once Authentication has been activated, click the "Google" button in the Sign-in providers section.

When the settings screen appears, click the "Enable" toggle button to enable the Google sign-in provider, then select "Project support email" and then click the "Save" button.

Coding preparation

Run the following commands to prepare for coding.

mkdir firebase-auth-google
cd firebase-auth-google
npm init -y
npm install --save firebase
npm install --save-dev webpack webpack-cli webpack-dev-server
touch app.js firebase-config.json index.html webpack.config.js

Coding

webpack.config.js

Open webpack.config.js in the editor and enter the following content.

Click to go to webpack.config.js

index.html

Open index.html in the editor and enter the following content.

Click to go to index.html

firebase-config.json

Open firebase-config.json in the editor and enter the copied content.

Click to go to firebase-config.json

app.js

Open app.js in the editor and enter the following content.

Click to go to app.js

The points are as follows:

  1. Load firebase-config using fetch function.
  2. Call the initializeApp function to initialize the application.
  3. Call the getAuth function to initialize Authentication.
  4. Use the onAuthStateChanged function to register an event handler that will be called when the authentication state changes. In this example, in addition to showing / hiding the section contained in the web page depending on whether you are signed in, we are accessing user.uid to get the user ID.
  5. When the user clicks the "Sign in" button (buttonSignin), call the signInWithRedirect function to go to the Google login page.
  6. When the user clicks the "Sign out" button (buttonSignout), call the signOut function to sign out.

Operation check

Run the following command in the terminal to start the server.

npx webpack serve

Go to http://localhost:8080/ in the browser and make sure you only see the sign in / sign up section.

Check that clicking the "Sign in" button will take you to the Google login page.

After signing in, you will be returned to the app page and check that your user ID and "Sign out" button are displayed.

Check that clicking the "Sign out" button hides the user information and sign out section and shows the sign in section.

Conclusion

I was wondering if an authorization code was passed using the query parameter when returning from the Google login page to the application page, but it seems that it is not so and I am curious about how it works. I would appreciate your guidance if you have any details, and I welcome your comments on other opinions and impressions. Thank you for reading!

Related article

/node_modules/
/firebase-config.json
/package-lock.json
# Do not ignore package-lock.json other than gist
import {initializeApp} from "firebase/app"
import {
getAuth,
onAuthStateChanged,
GoogleAuthProvider,
signInWithRedirect,
signOut,
} from "firebase/auth"
main()
async function main () {
try {
const el = {
sectionSignin: document.querySelector('#sectionSignin'),
sectionUser: document.querySelector('#sectionUser'),
sectionSignout: document.querySelector('#sectionSignout'),
buttonSignin: document.querySelector('#buttonSignin'),
buttonSignout: document.querySelector('#buttonSignout'),
uid: document.querySelector('#uid'),
}
const response = await fetch('firebase-config.json') // <1>
const firebaseConfig = await response.json()
const app = initializeApp(firebaseConfig) // <2>
const auth = getAuth(app) // <3>
onAuthStateChanged(auth, (user) => { // <4>
if (user) {
el.sectionSignin.style.display = 'none'
el.sectionUser.style.display = 'block'
el.sectionSignout.style.display = 'block'
el.uid.innerHTML = user.uid
} else {
el.sectionSignin.style.display = 'block'
el.sectionUser.style.display = 'none'
el.sectionSignout.style.display = 'none'
}
})
el.buttonSignin.addEventListener('click', async (event) => { // <5>
try {
event.preventDefault()
const provider = new GoogleAuthProvider()
await signInWithRedirect(auth, provider)
} catch (err) {
el.errorMessage.innerHTML = err.message
console.error(err)
}
})
el.buttonSignout.addEventListener('click', async (event) => { // <6>
try {
event.preventDefault()
await signOut(auth)
} catch (err) {
console.error(err)
}
})
} catch (err) {
console.error(err)
}
}
{
"apiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"authDomain": "xxxxxxxxxxxxxxxxxxxxxxxx.firebaseapp.com",
"projectId": "xxxxxxxxxxxxxxxxxxxxxxxx",
"storageBucket": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"messagingSenderId": "000000000000",
"appId": "0:000000000000:web:xxxxxxxxxxxxxxxxxxxxxx"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to sign in with email and password using Firebase Auth</title>
</head>
<body>
<h1>How to sign in with email and password using Firebase Auth</h1>
<section id="sectionSignin">
<h2>Sign in / Sign up</h2>
<form>
<button type="submit" id="buttonSignin">Sign in</button>
</form>
</section>
<section id="sectionUser">
<h2>User information</h2>
<dl>
<dt>uid</dt>
<dd id="uid"></dd>
</dl>
</section>
<section id="sectionSignout">
<h2>Sign out</h2>
<button type="button" id="buttonSignout">Sign out</button>
</section>
<script src="js/app.js"></script>
</body>
</html>
{
"name": "firebase-auth-google",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack serve"
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.8.1"
},
"dependencies": {
"firebase": "^9.7.0"
}
}
module.exports = {
mode: 'development',
entry: './app.js',
output: {
filename: 'js/app.js',
},
devtool: false,
devServer: {
client: false,
hot: false,
static: {
directory: __dirname,
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment