npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@gjw-react-oauth/google

v0.0.5

Published

React Google Oauth with latest GSI

Downloads

200

Readme

React Google Oauth with latest GSI

GJW React OAuth2 | Google

Google OAuth2 using the new Google Identity Services SDK. This package for React @gjw-react-oauth/google is used as replacement of previous Google Oauth SignIn.

Install

$ npm install @gjw-react-oauth/google@latest

# or

$ yarn add @gjw-react-oauth/google@latest

# or

$ pnpm install @gjw-react-oauth/google@latest

Git Repository

https://gitlab.cloudokyo.dev/vinhng/gjw-react-oauth

Seamless sign-in and sign-up flows

Sign In With Google

Add a personalized and customizable sign-up or sign-in button to your website.

personalized button

One-tap sign-up

Sign up new users with just one tap, without interrupting them with a sign-up screen. Users get a secure, token-based, passwordless account on your site, protected by their Google Account.

One-tap sign-up

Automatic sign-in

Sign users in automatically when they return to your site on any device or browser, even after their session expires.

Automatic sign-in

User authorization for Google APIs (with custom button)

OAuth 2.0 implicit and authorization code flows for web apps

The Google Identity Services JavaScript library helps you to quickly and safely obtain access tokens necessary to call Google APIs. Your web application, complete either the OAuth 2.0 implicit flow, or to initiate the authorization code flow which then finishes on your backend platform.

How to use

  1. Get your Google API client ID

Key Point: Add both http://localhost and http://localhost:<port_number> to the Authorized JavaScript origins box for local tests or development.

  1. Configure your OAuth Consent Screen

  2. Add Google Login Button to your UI

import { GoogleLoginButton } from "@gjw-react-oauth/google";

<GoogleLoginButton clientId="<your_client_id>" {...other properties}>...</GoogleLoginButton>;

Understand the changing on new GSI process

  • GSI supports full process of SignIn with built-in login and support limited on customized login button.
  • For Oauth2, GSI does not support id_token in return. Instead, GSI supports 2 kinds of way to login.
    • Implicit: returns access_token, which can use to access directly to google API endpoint.
    • Authentication Code: returns code which can use to get the id_token. If you want to custom the login button, this flow is recommended.

Sign In With Google Built-In

import { GoogleLoginButton } from "@gjw-react-oauth/google";

<GoogleLoginButton
  clientId={clientId}
  loginType="built-in"
  mode={"popup"}
  useOneTap={true / false}
  onSuccess={onSuccess}
/>;

One-tap dialog appeared at right top corner

useOneTap prop true

If you are using one tap login, when logging user out consider this issue may happen, to prevent it call googleLogout when logging user out from your application.

Automatic sign-in when only one account logged in the current session

auto_select prop true on idConfiguration

<GoogleLoginButton
  clientId={clientId}
  loginType="built-in"
  mode={"popup"}
  idConfiguration={{ auto_select: true }}
  onSuccess={onSuccess}
/>

Custom login button (implicit & authorization code flow)

import { GoogleLoginButton } from "@gjw-react-oauth/google";

<GoogleLoginButton clientId={clientId} loginType="custom" responseType="code" onSuccess={onSuccess}>
  SignIn with Custom button
</GoogleLoginButton>;

Implicit flow

responseType prop access-token Access google directly on client side for user profile

const OAUTH_USER_INFO_URL = "https://www.googleapis.com/oauth2/v3/userinfo";

export default async function getUserInfos(token: googleOauth2.TokenResponse, endpoint?: string) {
  try {
    const res = await fetch(`${endpoint || OAUTH_USER_INFO_URL}?access_token=${token.access_token}`);
    return (await res.json()) as googleOauth2.UserInfo;
  } catch (e) {
    console.error(e);
  }
}

Authorization code flow

responseType prop code

Requires backend to exchange code with access token

Sample code in backend to exchange the code

const auth = require("google-auth-library");

async function exchangeAndVerifyToken(authenticationCode) {
  try {
    const client = new auth.OAuth2Client({
      clientId: "<< application's id >>",
      clientSecret: "<< application secret key >>",
      redirectUrl: "postmessage",
    });
    const { tokens } = await client.getToken(authenticationCode);
    if (!tokens) {
      throw new Error("Invalid authentication code");
    }

    const ticket = await client.verifyIdToken({
      idToken: tokens.id_token,
      audience: client_id,
    });
    return ticket.getPayload();
  } catch (e) {
    console.error(e);
  }
}

API

GoogleOAuthProvider

| Required | Prop | Type | Description | | :------: | ------------------- | ---------- | --------------------------------------------------------------------------- | | ✓ | clientId | string | Google API client ID | | | onScriptLoadSuccess | function | Callback fires on load gsi script success | | | onScriptLoadError | function | Callback fires on load gsi script failure |

GoogleLogin

| Required | Prop | Type | Description | | :------: | ---------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ✓ | onSuccess | (response: CredentialResponse) => void | Callback fires with credential response after successfully login | | | onError | function | Callback fires after login failure | | | type | standard | icon | Button type type | | | theme | outline | filled_blue | filled_black | Button theme | | | size | large | medium | small | Button size | | | text | signin_with | signup_with | continue_with | signin | Button text. For example, "Sign in with Google", "Sign up with Google" or "Sign in" | | | shape | rectangular | pill | circle | square | Button shape | | | logo_alignment | left | center | Google logo alignment | | | width | string | button width, in pixels | | | locale | string | If set, then the button language is rendered | | | useOneTap | boolean | Activate One-tap sign-up or not | | | promptMomentNotification | (notification: PromptMomentNotification) => void | PromptMomentNotification methods and description | | | cancel_on_tap_outside | boolean | Controls whether to cancel the prompt if the user clicks outside of the prompt | | | auto_select | boolean | Enables automatic selection on Google One Tap | | | ux_mode | popup | redirect | The Sign In With Google button UX flow | | | login_uri | string | The URL of your login endpoint | | | native_login_uri | string | The URL of your password credential handler endpoint | | | native_callback | (response: { id: string; password: string }) => void | The JavaScript password credential handler function name | | | prompt_parent_id | string | The DOM ID of the One Tap prompt container element | | | nonce | string | A random string for ID tokens | | | context | signin | signup | use | The title and words in the One Tap prompt | | | state_cookie_domain | string | If you need to call One Tap in the parent domain and its subdomains, pass the parent domain to this attribute so that a single shared cookie is used | | | allowed_parent_origin | string | string[] | The origins that are allowed to embed the intermediate iframe. One Tap will run in the intermediate iframe mode if this attribute presents | | | intermediate_iframe_close_callback | function | Overrides the default intermediate iframe behavior when users manually close One Tap | | | itp_support | boolean | Enables upgraded One Tap UX on ITP browsers | | | hosted_domain | string | If your application knows the Workspace domain the user belongs to, use this to provide a hint to Google. For more information, see the hd field in the OpenID Connect docs |

useGoogleLogin (Both implicit & authorization code flow)

| Required | Prop | Type | Description | | :------: | --------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | flow | implicit | auth-code | Two flows, implicit and authorization code are discussed. Both return an access token suitable for use with Google APIs | | | onSuccess | (response: TokenResponse\|CodeResponse) => void | Callback fires with response (token | code) based on flow selected after successfully login | | | onError | (errorResponse: {error: string; error_description?: string,error_uri?: string}) => void | Callback fires after login failure | | | onNonOAuthError | (nonOAuthError: NonOAuthError) => void | Some non-OAuth errors, such as the popup window is failed to open or closed before an OAuth response is returned. popup_failed_to_open | popup_closed | unknown | | | scope | string | A space-delimited list of scopes that are approved by the user | | | enable_serial_consent | boolean | defaults to true. If set to false, more granular Google Account permissions will be disabled for clients created before 2019. No effect for newer clients, since more granular permissions is always enabled for them. | | | hint | string | If your application knows which user should authorize the request, it can use this property to provide a hint to Google. The email address for the target user. For more information, see the login_hint field in the OpenID Connect docs | | | hosted_domain | string | If your application knows the Workspace domain the user belongs to, use this to provide a hint to Google. For more information, see the hd field in the OpenID Connect docs |

useGoogleLogin (Extra implicit flow props)

| Required | Prop | Type | Description | | :------: | ------ | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | prompt | '' | none | consent | select_account | defaults to 'select_account'. A space-delimited, case-sensitive list of prompts to present the user | | | state | string | Not recommended. Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response |

useGoogleLogin (Extra authorization code flow props)

| Required | Prop | Type | Description | | :------: | -------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | ux_mode | popup | redirect | The UX mode to use for the authorization flow. By default, it will open the consent flow in a popup. Valid values are popup and redirect | | | redirect_uri | string | Required for redirect UX. Determines where the API server redirects the user after the user completes the authorization flow The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client which you configured in the API Console and must conform to our Redirect URI validation rules. The property will be ignored by the popup UX | | | state | string | Recommended for redirect UX. Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response | | | select_account | boolean | defaults to 'false'. Boolean value to prompt the user to select an account |

useGoogleOneTapLogin

| Required | Prop | Type | Description | | :------: | ------------------------ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ✓ | onSuccess | (response: CredentialResponse) => void | Callback fires with credential response after successfully login | | | onError | function | Callback fires after login failure | | | promptMomentNotification | (notification: PromptMomentNotification) => void | PromptMomentNotification methods and description | | | cancel_on_tap_outside | boolean | Controls whether to cancel the prompt if the user clicks outside of the prompt | | | hosted_domain | string | If your application knows the Workspace domain the user belongs to, use this to provide a hint to Google. For more information, see the hd field in the OpenID Connect docs |