Code Monkey home page Code Monkey logo

react-oauth's Introduction



react-oauth's People

Contributors

abereghici avatar alexbensimon avatar biniama avatar danfsd avatar digitalnaut avatar github-actions[bot] avatar jcayabyab avatar jimcapel avatar kembly avatar liviogama avatar micahramirez avatar momensherif avatar niksauer avatar p1yu5h avatar yuriburk avatar zhumingcheng697 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-oauth's Issues

Error with useGoogleLogin: `Google OAuth components must be used within GoogleOAuthProvider`

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;

image

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?

TypeError: Cannot read properties of undefined (reading 'requestAccessToken')

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!

how to get access to user profile and email?

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"
}

How to silent login?

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?

[GSI_LOGGER-TOKEN_CLIENT]: Set token failed. Gapi.client.setToken undefined.

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!

googleLogout function

How exactly is this function supposed to work?
In source code I see only:
declare function googleLogout(): void;

Why docs recommend against using `state` value in `useGoogleLogin`

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.

Custom button onSuccess not returning credential

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!

User information is missing

Thank you so much for momen for creating this package, I am having following issue:

  1. Unable to access the user information like username or email or profile image etc.
  2. earlier there was profile object through which we can access the profileObj key and get all the information.

getting response on success is only clientId, credential and select_by.

Please help me with this issue.

Refresh expired id token (JWT) on client using TokenClient.requestAccessToken()?

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?

Failing to resolve module 'react/jsx-runtime'

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?

Neither onSuccess nor onError are not called when using hook

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.

Is there a way to prevent the signin with google button from turning into "Sign in as <user_name>"?

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

What I want

image

What I'm getting

image

How to detect Google oauth window closed action from user?

I cannot detect close google sign in popup. Please help me!

image

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',
    })

JWT instead of access_token?

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 can't use custom login button

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.

Export type definitions

Hey, first of all thanks for all the effort put into this.
Would it be possible to export type definitions like for example GoogleLoginProps?

Locale property is not working?

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?

Origins with and without ports

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!

Get more data on CredentialResponse

Currently, GoogleLogin onSuccess props is returning CredentialResponse which only has clientId, credential, and select_by. Are there any methods I can use to get more information like user profile name or profile image on response, for example below image? Thank you in advance!
image

How to recognize start of authentication flow?

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?

Customization of GoogleLogin

<GoogleLogin

                              buttonText="Sign in with Google"
                              onSuccess={responseGoogle}
                              onError={errorResponseGoogle}
                              // useOneTap={true}
                             >
                    </GoogleLogin>

how to customize these button ? any example..

Expiration time of access token

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

Getting Error: Google OAuth components must be used within GoogleOAuthProvider

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:

image

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;


Production build error "Failed to set the 'src' property on HTMLScriptElement

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.

image

if i open the traceback, the issue is highlighted
image

How to use "redirect" instead of "popup" when using useGoogleLogin?

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!

onSuccess operations when ux_mode is redirect

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!

Default GoogleLogin button does not change after login

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:

  • I see the Google button with "Sign in as xxx"
  • I am able to click the button and get the popup to choose my Google account to login with.
  • After selecting my Google account, the popup closes and I see the credentialResponse logged to the console.

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!

Why may happen no console logs after I selected account in Google auth popup?

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?

Provide credential (jwt) in response for custom button

import { useGoogleLogin } from '@react-oauth/google';

const login = useGoogleLogin({
onSuccess: credential=> console.log(credential),
flow: 'jwt',
});

<MyCustomButton onClick={() => login()}>
Sign in with Google ๐Ÿš€{' '}
;

useGoogleLogin works in development but fails with production build

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.

profile.Obj missing from the success response

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?

GoogleLogin and useGoogleLogin are not returning the same response

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,
  })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.