Authentication flow for MERN stack application using google OAuth 2.0.
This oauth flow is more secure and you don't have to reload your react app and go through multiple redirections to authenticate client.
And the image blow is from google docs
git clone https://github.com/Shahzayb/mern-google-login.git
cd mern-google-login
npm install
cd client & npm install
Visit the Google API Console to obtain OAuth 2.0 credentials such as a client ID and client secret that are known to both Google and your application. Don't store your client secret in your React app. You only need client id in your react app to get the authorization grant code. And you should store client secret in node app.
Go to Google API Console. And select your project & then add JavaScript Origins Url
This is a url of client side react app
You'll notice in my code that I set the redirect_uri
to postmessage
, its because we need the authorization grant code without any redirection
- execute these commands
cd client
touch .env.local
- open
.env.local
file & enterREACT_APP_GOOGLE_CLIENT_ID=your client id provided by google
From the root directory of the project, type:
mkdir config
cd config
touch dev.env
Note: These commands are for Mac/Linux users only. Windows users should type these commands in git bash
Now open the dev.env file and add GOOGLE_CLIENT_ID=value from google apis
, GOOGLE_CLIENT_SECRET=value from google apis
npm run dev
if you want more information, then please read the one-time-code flow implementation
Please help me with the documentation and improve the code. I'll appreciate that. For changes, please open an issue first to discuss what you would like to change.