I go then authentication token using a package. You can get this token following other ways also. Install a npm package for your google login. Check this npm package.
Add scope and flow in the GoogleLogin function to get the authentication code.
import { GoogleLogin } from '@react-oauth/google';
<GoogleLogin
scope: 'https://mail.google.com/',
flow: 'auth-code',
onSuccess={credentialResponse => {
console.log(credentialResponse);
}}
onError={() => {
console.log('Login Failed');
}}
/>;
Success response will look like this:
{
authuser: "0",
code: "********KAjJZmv4xLvbAIHeySg",
hd: "myalice.ai",
prompt: "consent",
}
Here, we need the code part only.
Generating refresh and access token:
Send the code you got from the response inside the payload.
let payload = {
grant_type: 'authorization_code',
code: "********KAjJZmv4xLvbAIHeySg",
client_id: '******.googleusercontent.com',
client_secret: 'GOCS*******m5Qzg',
redirect_uri: 'http://localhost:3000',
};
axios
.post(`https://oauth2.googleapis.com/token`, payload, {
headers: {
'Content-Type': 'application/json;',
},
})
.then((res: any) => {
return res.data;
})
.then((response: any) => {
console.log('refresh token: ', response);
})
.catch((err) => console.log('err: ', err));
You will get a response like this:
{
access_token: "********KAjJZmv4xLvbAIHey",
expires_in: 3599,
id_token: "***************VeM7cfmgbvVIg",
refresh_token: "***************VeM7cfmgbvVIg",
scope: "https://www.googleapis.com/auth/gmail.readonly openid
.....
.....
https://mail.google.com/",
token_type: "Bearer",
}
Save your refresh and access token.
Now you can use refresh token to generate new access token!
Here is an article on how you can integrate this on your react application. You can check this out for more details.