momensherif / react-oauth Goto Github PK
View Code? Open in Web Editor NEWGoogle OAuth2 using the new Google Identity Services SDK for React ๐
Home Page: https://www.npmjs.com/package/@react-oauth/google
License: MIT License
Google OAuth2 using the new Google Identity Services SDK for React ๐
Home Page: https://www.npmjs.com/package/@react-oauth/google
License: MIT License
import React from "react";
import { GoogleOAuthProvider, useGoogleLogin } from "@react-oauth/google";
const CLIENT_ID = process.env.REACT_APP_GOOGLE_OAUTH_CLIENT_ID || "";
interface props {
setAccessToken: React.Dispatch<React.SetStateAction<string>>;
}
const Authorize: React.FC<props> = ({ setAccessToken }) => {
const login = useGoogleLogin({
onSuccess: (tokenResponse) => console.log(tokenResponse),
});
return (
<GoogleOAuthProvider clientId={CLIENT_ID}>
<div id="authorizeButton">
<button onClick={() => login()} />
</div>
</GoogleOAuthProvider>
);
};
export default Authorize;
Uncaught Error: Google OAuth components must be used within GoogleOAuthProvider
Getting the following error above with the respective code. I am using useGoogleLogin
so I can manually define the scope's I require of the user. I didn't have any issuing using GoogleLogin
within GoogleOAuthProvider
. I'm encountering this error only when using useGoogleLogin
.
Is this a bug or am I not properly implementing the auth?
We're using the useGoogleLogin()
hook and the library is working great overall but we're seeing a low volume of type error bugs: TypeError: Cannot read properties of undefined (reading 'requestAccessToken')
. ~80% on Mobile Chrome Web. It looks like .requestAccessToken
is part of this ref. Any ideas on a potential fix or something we can do in our client-side code? Thanks!
Can I somehow customize the token expiration period? As far as I understand it is 1 hour by default.
i've tried to get access to these data using scopes, like this:
const googleLoginHandler = useGoogleLogin({
onSuccess: googleSuccessHandler,
onError: googleFailureHandler,
scope: ["profile"],
//scope: ["https://www.googleapis.com/auth/userinfo.profile"],
//scope: ["openid", "profile", "email"],
//scope: ['openid', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']
});
but I always get a response with a scope with the same links above or get an invalid scope message in the pop-up window.
example of the res:
{
"access_token": "ya29.a0ARrdaM_pT_cxBuNfQOoU345ZirNrxfhBkOI3YXRtrmBA9PsQZv7Ma3ACKGe_0W-XLCr3YYYs-1eyocKRdeo32eeg4so-koNaxPE_JL8hrbDcVKJMKQZa9NCh2jwnR9eNDMQrAKAbomIqbIuegvbelK9eOiEw",
"token_type": "Bearer",
"expires_in": 3599,
"scope": "email profile https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email openid",
"authuser": "0",
"prompt": "none"
}
Hi @MomenSherif, thank you for your library. In other similar libraries there was a silent login feature, where the user would silently login again in the app when launching it. How does it work here?do i need to login each time i open the app from the beginning?how do i check if a user is still logged in when i launch it?
Hi,
I have followed your example and was able to setup a google login button however when selecting an account in the popup a warning appears: [GSI_LOGGER-TOKEN_CLIENT]: Set token failed. Gapi.client.setToken undefined.
and I am not getting any code back. The success method is fired though with the following data:
{
"access_token": "[token here]",
"token_type": "Bearer",
"expires_in": 3599,
"scope": "email profile openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
"authuser": "0",
"prompt": "none"
}
but node code
property
What I am doing wrong?
in my script:
const login = useGoogleLogin({
onSuccess: onGoogleLoginHandler,
onError: onGoogleFailureHandler,
});
<button onClick={() => login()}>login</button>
in my app:
return (
<GoogleOAuthProvider clientId={config.GOOGLE_CLIENT_ID} >
...app code...
</GoogleOAuthProvider>
);
Thanks!
How exactly is this function supposed to work?
In source code I see only:
declare function googleLogout(): void;
The "useGoogleLogin (Extra implicit flow props)" section of the README says the state
value is "Not recommended". Why is that?
Google's OpenID / Oauth2 docs recommend using state to prevent CSRF attacks:
You must protect the security of your users by preventing request forgery attacks. The first step is creating a unique session token that holds state between your app and the user's client. You later match this unique session token with the authentication response returned by the Google OAuth Login service to verify that the user is making the request and not a malicious attacker. (source)
I'm just curious if there's something I'm missing.
Hi, I'm implementing a custom login button using the useGoogleLogin
as described in the documentation, but I'm not getting the clientId
, credential
, and rest of the response data that It's supposed to get, instead I get:
access_token: "ya29.a0ARrdaM_--q837N6fVSybji2oU_XrzjUWDGCnrSyTjJ4Uo2dAwFb9vv77C05HW-
STDy50qVlivAqGEDKi22elPkv9fwdR_nRk0JxVPxVs78gVm7ICR9WXUS8zLvfLeDY2mpHExRcZ8po31ZG3OJkeJfAV3AThXw"
authuser: "0"
expires_in: 3599
hd: "kairosds.com"
prompt: "none"
scope: "email profile https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email"
token_type: "Bearer"
and trying to decode the access_token
doesn't give me the profile info.
My component:
<GoogleButton
busy={busy}
onButtonPressed={handleGoogleSignin}
platform={platform}
label={formatMessage(TEXT.GOOGLE_BUTTON)}
testID="google-register-button"
/>
My Handler:
const handleGoogleSignin = useGoogleLogin({
onSuccess: tokenResponse => console.log('MIGRATION: ', tokenResponse),
});
Is there any step I'm skipping? I already wrapped my app in the provider.
Thanks!
Is there something like onCancel
on the pop-up?
Thank you so much for momen for creating this package, I am having following issue:
getting response on success is only clientId, credential and select_by.
Please help me with this issue.
Part of this was previously discussed in Issue 9 which ended with the reasonable recommendation to use the Authorization code flow and have the backend obtain access, refresh and id tokens.
However, I did find some new information regarding the possibility of refreshing the id token (JWT) on the client (React) side and thought it might make sense to create a new issue for this specific question... Thanks again @MomenSherif for your patience. ๐ฅ
Background:
Possibly a lot of folks interested in this new react-oath library have previously used the popular react-google-login library. JWT token expiration after 1 hour was an issue people also struggled with using the react-google-login as seen in numerous Github issues on the react-google-login project.
There's some confusion (at least for me) whether it is possible to refresh the id token (JWT) from the client without requiring both the client id and secret. I did find this Blog post which provides a solution using the deprecated gapi library: Add Google Login to your React Apps in 10 mins.
As discussed in the blog post (and the code in Github):
This function checks for expires_in timestamp or our custom time (before the token expires) and calls reloadAuthResponse which is a util function provided by the library and it handles refresh_token and obtains new tokenId.
As far as I can tell, this reloadAuthResponse() function does get a new id token with new expiration date without requiring both the client id and secret on in React.
Google's Migrate to Google Identity Services does mention replacing GoogleUser.reloadAuthResponse() with TokenClient.requestAccessToken() and states:
Create a single reentrant function containing requestAccessToken(), call it when an access token is first needed, and later, after the existing token expires and Google API calls return a 401 Unauthorized status code response.
Do I understand correctly this may be a way using the new API to replace expired JWT tokens? Or is this specific to requesting new access tokens?
How can I get id_token
from a successful login?
Hello, I'm migrating from @react-google-login because the deprecation of old Google API, but I'm getting this error while building my app in local:
Failed to compile.
../node_modules/@react-oauth/google/dist/index.esm.js
Module not found: Can't resolve 'react/jsx-runtime' in 'path/to/my/project/node_modules/@react-oauth/google/dist'
I'm using the following versions:
"react": "16.10.2",
"react-dom": "16.10.2",
"typescript": "3.9.5",
"@react-oauth/google": "^0.2.1",
... rest of dependencies ommited for brevity
Thanks in advance!
Update: After realising that jsx-runtime is from react 17 (duh me), is there any way to make this library compatible with react 16?
When I clicked the button, it successfuly show the popup, however it doesn't do anything after logging in (onSuccess/onError not fired). Here is the code:
const handleGoogleLogin = useGoogleLogin({
onSuccess: (res) => console.log(res),
onError: (res) => console.log(res),
flow: 'auth-code'
});
Everything works in development, but not in a production website.
I've benn trying to use the signin with google button on a project, but I have a problem. After a few seconds, the button automatically turns into "Sign in as ".
That isn't really an issue, except for the fact that it creates a very odd padding inside its iframe (which I can't alter with CSS) and the resulting white background kinda breaks the look of any page that doesn't have a white background itself.
See the screenshots for context
I cannot detect close google sign in popup. Please help me!
Coding:
const responseGoogle = useGoogleLogin({
onSuccess: (response: CodeResponse) => {
if (response.code) {
dispatch(
authSocialSlice.onRequestLoginBySocial({
provider: PROVIDER_LOGIN.GOOGLE as ProviderLoginTypes.Provider,
token: response.code,
})
)
}
},
onError: () => {
onCloseToastAndLoading()
},
flow: 'auth-code',
})
I want to create my own custom Google login button and the design given by Google when using the GoogleLogin component does look too good for me to use.
Is it possible to get a JWT instead of the access_token when using useGoogleLogin hook, like when using the GoogleLogin component?
Thanks!
I couldn't use it with custom button. It wants auth provider, but useGoogleLogin cannot be used in auth provider. Can you help me? It would be nice if the client id could be sent as options in useGoogleLogin.
Hey, first of all thanks for all the effort put into this.
Would it be possible to export type definitions like for example GoogleLoginProps
?
To be honest I'm not sure if I am doing something wrong but it seems that the locale
property of the the GoogleLogin
component isn't working, in your and in the google documentation is stated that: locale: string
, e.g. "zh_CN", but even the example isn't working.
Is this the case or I miss understhood something?
Hello @MomenSherif,
regarding this part of the installation instructions:
Key Point: Add both http://localhost and http://localhost:<port_number> to the Authorized JavaScript origins box for local tests or development.
Do you know why we need to add http://localhost
when we will use a certain port locally?
Is this something on the lib side, or is this at another layer?
Just curious, as it's been a source of difficulty in manual testing.
Thank you!
While migrating from react-google-login I noticed that there is no way to get notified when the authentication flow actually starts (onRequest
), i.e. when the user has clicked the Sign in with Google button. Such a callback, however, is needed to instruct other components to reset their state, especially when performing multiple login attempts upon failure and mixing this with a password-based sign in or other social providers.
Previously, this was possible by overloading the button's onClick handler. This approach does not work anymore since the button will be injected as an iframe.
How can I now recognize when a user has clicked Sign in with Google?
Hello MomenSherif
I am using react-oauth package so it is working in localhost but it does not work in production environment.
Can suggest how to solve these issue.
It is screen shot of our live production environment issues
https://user-images.githubusercontent.com/53229705/177474714-71f29ea5-2597-4d0a-91e7-634f43979009.png
<GoogleLogin
buttonText="Sign in with Google"
onSuccess={responseGoogle}
onError={errorResponseGoogle}
// useOneTap={true}
>
</GoogleLogin>
how to customize these button ? any example..
how to get expiration time with the help of an access token. In general, I used to decode the token and use the exp property to get that. But I am unable to get the expiration time with the access token. I want to logout after the token expires
Hello. I'm trying to get auth code from google and send it to server side to get tokens. But when I wrapped my custom button to the GoogleOAuthProvider component I got the error like on the screenshot:
I'm doing everything like in documentation, but don't understand where I could make a mistake...
this is my component's code:
/* eslint-disable react/button-has-type */
import { GoogleOAuthProvider, useGoogleLogin } from '@react-oauth/google';
import { Button, message } from 'antd';
import { setApiHeader } from 'api/axios';
import { userAuth } from 'api/requests/userAuth';
import React from 'react';
import { useHistory } from 'react-router-dom';
import { localStorageKeys } from 'resources/localStorageKeys';
import { saveState } from 'utils/localStorage';
const GoogleAuth = () => {
const clientId = process.env.REACT_APP_GOOGLE_CLIENT_ID || '';
const history = useHistory();
const login = useGoogleLogin({
onSuccess: async (res: any) => {
try {
const { data } = await userAuth(res);
saveState(data, localStorageKeys.radiatorUser);
setApiHeader('Authorization', `Bearer ${data?.token}`);
history.push('/');
if (data) void message.success('Success');
} catch (error) {
void message.error(error.message);
}
},
flow: 'auth-code',
});
return (
<GoogleOAuthProvider clientId={clientId}>
<Button onClick={() => login()}>Sign in with Google ๐ </Button>
</GoogleOAuthProvider>
);
};
export default GoogleAuth;
Working in development env, everything works great, but as soon as i make a release and the code gets hosted, the application crashes on initial load (only white screen is displayed)
Error displayed: react-dom.production.min.js:216 TypeError: Failed to set the 'src' property on 'HTMLScriptElement': This document requires 'TrustedScriptURL' assignment.
Hello, I wanted to use a custom button so I used useGoogleLogin. I also wanted to use redirection instead of a popup but I'm not sure how to do that. Here's my failed attempt:
const googleLogin = useGoogleLogin({
ux_mode: "redirect",
redirect_uri: "http://localhost:3000/preview",
onSuccess: success => console.log("SUCCESS: ", success),
onError: error => console.log("ERROR: ", error),
});
It's still using the popup so I guess I'm not using it correctly. Any help would be greatly appreciated. Thanks!
Hello, I'm using redirection instead of popup to login. The the onSuccess prop doesn't seem to be triggered. Am I using this wrong or is this just the expected behavior?
const googleLogin = useGoogleLogin({
flow: 'auth-code',
select_account: true,
ux_mode: "redirect",
redirect_uri: "http://localhost:3000/preview/",
onSuccess: async ({ access_token }) => {
{...}
},
onError: () => {...},
});
Thanks!
First off I just want to say thanks for your efforts on this project. It's appreciated. I am trying to replace react-google-login in my React app with your react-oauth due to challenges around refresh tokens and the use of the deprecated Google API.
I am following the instructions on the ReadMe for using GoogleLogin. I think it's mostly working because:
Therefore, I think it's working correctly. However, after that the Google button still shows "Sign in as xxx" . Is that the expected behavior? Or am I missing something in my understanding?
If you don't mind, can I use this Issue for an additional question? As mentioned, I am trying to avoid dealing with refresh tokens. As the Google docs state "User sign-in no longer requires you to understand or work with OAuth2 authorization codes, access tokens, or refresh tokens." I need to send a JWT to my Resource Server (not Google) which will validate the JWT with Google. If I understand correctly, I can get the JWT token from the returned credential and send that to my Resource Server. However, the JWT still expires in 1 hour right? I'm not understanding how this new API solves my problem with having to refresh the token. What am I missing?
Thanks again for your efforts and your patience! Cheers!
Hi! Using this code:
import { GoogleLogin } from '@react-oauth/google';
<GoogleLogin
onSuccess={credentialResponse => {
console.log(credentialResponse);
}}
onError={() => {
console.log('Login Failed');
}}
/>;
Also wrapped app component with GoogleOAuthProvider . However when I click button and then select account in Google auth popup, I see nor success, neither error logs. What could be the reason?
how to get the user profile info after successful login?
So Im Using GoogleLogin component and im getting the credentials from google.
So the next step would be to send that to my api server and decode it, my question is how?
import { useGoogleLogin } from '@react-oauth/google';
const login = useGoogleLogin({
onSuccess: credential=> console.log(credential),
flow: 'jwt',
});
<MyCustomButton onClick={() => login()}>
Sign in with Google ๐{' '}
;
I am using the implicit flow to get the tokenResponse from google and then send the token to my backend. Everything works perfectly fine in local development but when I build the react for production, the login does not work at all. There are no errors received at all.
const googleLogin = useGoogleLogin({
flow: "implicit",
onSuccess: (tokenResponse) => {
console.log(tokenResponse);
// Send the google token to the backend to get access and refresh tokens
dispatch(
googleLoginRequest({
access_token: tokenResponse.access_token,
})
);
},
onError: (errorResponse) => console.log(errorResponse),
});
I am not sure if there is something that is not being included in the build or not because I have cleared cache, changed browsers and it all seems to work in development and not in production with the react build.
I noticed GoogleLogin
doesn't have a prop for scope, but useGoogleLogin
does. Is it possible for me to use GoogleLogin
components button but with either specifying a prop or overloading the onClick to use useGoogleLogin
instead?
The response that I am getting after signing the user is an object with only three items: my client id, credential, and select_by. Shouldn't I get more information like the profile.Obj which contains user's name, email, display picture so that I can show them on my web app after the user signs in? Am I missing something?
How can we access the details like email-id, profile picture link, Name and stuffs like that for the current logged in user.
How can I use a custom login button? GoogleLogin component and useGoogleLogin aren't returning the same response
With GoogleLogin the response is:
{
clientId: 'XXXXXX,
credential: 'credential_token',
select_by: 'btn'
}
With useGoogleLogin, the response is:
{
access_token: "xxxxxxxxx",
authuser: "0",
expires_in: 3599,
hd: "domain.com"
prompt: "none"
scope: "email profile openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
token_type: "Bearer"
}
The hook isn't supposed to return the credential key/value as the component does?
I am sending the credential key/value to my server which verifies it to send me back the user profile.
import { OAuth2Client } from 'google-auth-library'
// ...
const userProfile = googleClient.verifyIdToken({
idToken: req.body.credentials,
audience: req.body.clientId,
})
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.