Embark on a journey to enhance the user authentication experience in your web applications by delving into the powerful synergy of Google OAuth2, Django, and React. Our latest blog is your comprehensive guide to seamlessly integrating Google OAuth2 authentication into your Django backend while harnessing the dynamic capabilities of React on the frontend.
We use these package in this tutorial
Getting react app started and adding env vars
cd <react app>
Make some env variables in a .env file in root of app and add the client_id and client secret that we got from Django admin applications and also add your google client id that you got from google api in our .env file
Note:
all the env var should be start with REACT_APP_
REACT_APP_GOOGLE_CLIENT_ID=126073961034-gi3pldgf14io838rnk9i1e1ld.apps.googleusercontent.com
REACT_APP_DRF_CLIENT_ID=JekrFHZYdM9BNJgX1u7tPANoSRwvBgseR
REACT_APP_DRF_CLIENT_SECRET=VdVZZP7gR0vqbgypQLvgYHDd8RJuyf3oikq16zh3ekNEZ3zVehssd85t4fPyQll5imHrgtaoMPSIlOQ51nWgIlrTuDQtBObFVo1NztRhpOS0thoW6yEkiqt2T
Now install @react-oauth/google by using command
npm install @react-oauth/google@latest
# if you using yarn
yarn add @react-oauth/google@latest
Now make some changes in index.js file to Wrap your application with
GoogleOAuthProvider
//add this import on top of index.js file
import { GoogleOAuthProvider } from '@react-oauth/google';
// get the REACT_APP_GOOGLE_CLIENT_ID that we created in .env file like this
const googleClientId = process.env.REACT_APP_GOOGLE_CLIENT_ID;
// wrap our app with GoogleOAuthProvider
<React.StrictMode>
<GoogleOAuthProvider clientId={googleClientId}>// add this
<app/>
</GoogleOAuthProvider>;// add this
</React.StrictMode>
Now make some changes in app.js file or you can create a new component Login.js and use that component like this
// Login.js
import React from 'react';
import { useGoogleLogin } from '@react-oauth/google';
const Login = () => {
const googleClientId = process.env.REACT_APP_GOOGLE_CLIENT_ID;
const drfClientId = process.env.REACT_APP_DRF_CLIENT_ID;
const drfClientSecret = process.env.REACT_APP_DRF_CLIENT_SECRET;
const baseURL = "http://localhost:8000";
async function handleGoogleLogin(credentialResponse) {
const backend = "google-oauth2";
const grant_type = "convert_token";
const dateToSend = {
token: credentialResponse.access_token,
backend: backend,
grant_type: grant_type,
client_id: drfClientId,
client_secret: drfClientSecret,
};
const newStringData = (JSON.stringify(dateToSend));
const response = await fetch(`${baseURL}/auth/convert-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: newStringData,
});
const dataFromApi = await response.json();
localStorage.setItem("access_token", dataFromApi.access_token);
localStorage.setItem("refresh_token", dataFromApi.refresh_token);
}
const login = useGoogleLogin({
onSuccess: tokenResponse => handleGoogleLogin(tokenResponse),
});
return (
<button onClick={() => login()}>
Sign in with Google 🚀
</button>
);
};
export default Login;
What are we doing in above code
In the above login.js file we created a function login that been called when we click the Button(Sign in with Google 🚀) in the function we basically making a post request on our backend http://localhost:8000/auth/convert-token and we sending the data
token: credentialResponse.access_token,
backend: “google-oauth2”,
grant_type: “convert_token”,
client_id: drfClientId,
client_secret: drfClientSecret,
token we get from the google button and our client_id and client_secret we get from our .env file and grant type should be “convert_token” and backend is“ google-oauth2” Then we will get our access and refresh token from backend and store them in local storageNow import login.js component in app.js and test it when you press the button and select the account to log in with our login.js send a request on backend and if all details are correct we will get a renponse 200 ok and refresh and access token
NOTE:
we can use axios as well but the axios throwing errors so we use fetch here
If it give you error like unauthorized access or forbidden then change the env vars and put the key direct in the request and then test it.
import Login from './Components/login/login';
function App() {
return (
<div className='row'>
<Login />
</div>
);
}
export default App;
The response should look like
{
"access_token": "Vcd5jHUJa09Hii13lCXQpBoM0k",
"expires_in": 36000,
"token_type": "Bearer",
"scope": "read write",
"refresh_token": "Dsd94Irg3X1qzjhRwgdUqTh0pgF"
}
You can check the token saved in network tab:
Checkout part 1 here : PART 1
Thankyou for reading I hope you learned a little from this article ✌️
👨💻 Programmer | ✈️ Love Traveling | 🍳 Enjoy Cooking | Building cool tech and exploring the world!
View more blogs by me CLICK HERE
Loading related blogs...
In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.