Socket
Socket
Sign inDemoInstall

google-oauth-gsi

Package Overview
Dependencies
0
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    google-oauth-gsi

A user-friendly API for GIS SDK, using the new [**Google Identity Services SDK**](https://developers.google.com/identity/gsi/web) ๐Ÿš€


Version published
Weekly downloads
349
decreased by-43.53%
Maintainers
1
Install size
62.7 kB
Created
Weekly downloads
ย 

Readme

Source

google-oauth-gsi (OAuth2 | Google)

A user-friendly API for GIS SDK, using the new Google Identity Services SDK ๐Ÿš€

  • โšก๏ธ Lightweight
  • ๐Ÿ“ฆ SSR friendly
  • ๐Ÿ•Š Dependency free
  • ๐Ÿ”‘ Fully Typed APIs
  • ๐Ÿ’ก Framework agnostic
  • FedCM Support

Install

$ pnpm add google-oauth-gsi@latest

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.
  • 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.
  • Automatic sign-in - Sign users in automatically when they return to your site on any device or browser, even after their session expires.

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. 127.0.0.1 is not a valid origin, use localhost instead.

  1. Configure your OAuth Consent Screen

  2. Create instance of GoogleOAuthProvider somewhere in your application.

import { GoogleOAuthProvider } from 'google-oauth-gsi';

export const googleProvider = new GoogleOAuthProvider({
    clientId: process.env.PUBLIC_GOOGLE_CLIENT_ID,
    onScriptLoadError: () => console.log('onScriptLoadError'),
    onScriptLoadSuccess: () => console.log('onScriptLoadSuccess'),
});

Sign In With Google

import { googleProvider } from './services';

const login = googleProvider.useGoogleLogin({
    flow: 'auth-code',
    onSuccess: (res) => console.log('Logged in with google', res),
    onError: (err) => console.error('Failed to login with google', err),
});

// Call login() on button click

One-tap

import { googleProvider } from './services';

const oneTap = googleProvider.useGoogleOneTapLogin({
    cancel_on_tap_outside: true,
    onSuccess: (res) => console.log('Logged in with google', res),
});

// Call oneTap() on onMount or onScriptLoadSuccess

or

import { buttonEl } from './somewhere';
import { googleProvider } from './services';

const renderButton = googleProvider.useRenderButton({
    useOneTap: true,
    element: buttonEl as HTMLElement,
    onError: () => console.error('Failed to render button'),
    onSuccess: (res) =>
        console.log('Logged in with google (render button)', res),
});

// Call renderButton() onMount or onScriptLoadSuccess

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.

import { googleLogout } from 'google-oauth-gsi';

googleLogout();

Custom login button (implicit & authorization code flow)

Implicit flow
import { googleProvider } from './services';

const login = googleProvider.useGoogleLogin({
    flow: 'implicit',
    onSuccess: (tokenResponse) => console.log(tokenResponse),
});

// Call login() when you need
Authorization code flow

Requires backend to exchange code with access and refresh token. If you need id_token then use this. Check examples to see how to do it.

import { googleProvider } from './services';

const login = googleProvider.useGoogleLogin({
    flow: 'auth-code',
    onSuccess: (codeResponse) => console.log(codeResponse),
});

// Call login() when you need
Checks if the user granted all the specified scope or scopes
import { hasGrantedAllScopesGoogle } from 'google-oauth-gsi';

const hasAccess = hasGrantedAllScopesGoogle(
    tokenResponse,
    'google-scope-1',
    'google-scope-2',
);
Checks if the user granted any of the specified scope or scopes
import { hasGrantedAnyScopeGoogle } from 'google-oauth-gsi';

const hasAccess = hasGrantedAnyScopeGoogle(
    tokenResponse,
    'google-scope-1',
    'google-scope-2',
);

API

GoogleOAuthProvider

RequiredPropTypeDescription
โœ“clientIdstringGoogle API client ID
onScriptLoadSuccessfunctionCallback fires on load gsi script success
onScriptLoadErrorfunctionCallback fires on load gsi script failure

useGoogleLogin (Both implicit & authorization code flow)

RequiredPropTypeDescription
flowimplicit | auth-codeTwo flows, implicit and authorization code are discussed. Both return an access token suitable for use with Google APIs
onSuccess(response: TokenResponse|CodeResponse) => voidCallback fires with response (token | code) based on flow selected after successfully login
onError(errorResponse: {error: string; error_description?: string,error_uri?: string}) => voidCallback fires after login failure
onNonOAuthError(nonOAuthError: NonOAuthError) => voidSome 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
scopestringA space-delimited list of scopes that are approved by the user
enable_serial_consentbooleandefaults 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.
hintstringIf 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_domainstringIf 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)

RequiredPropTypeDescription
prompt'' | none | consent | select_accountdefaults to 'select_account'. A space-delimited, case-sensitive list of prompts to present the user
statestringNot 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)

RequiredPropTypeDescription
ux_modepopup | redirectThe 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_uristringRequired 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
statestringRecommended 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_accountbooleandefaults to 'false'. Boolean value to prompt the user to select an account

useGoogleOneTapLogin

RequiredPropTypeDescription
โœ“onSuccess(response: CredentialResponse) => voidCallback fires with credential response after successfully login
onErrorfunctionCallback fires after login failure
promptMomentNotification(notification: PromptMomentNotification) => voidPromptMomentNotification methods and description
cancel_on_tap_outsidebooleanControls whether to cancel the prompt if the user clicks outside of the prompt
hosted_domainstringIf 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
use_fedcm_for_promptbooleanAllow the browser to control user sign-in prompts and mediate the sign-in flow between your website and Google. Defaults to false. See Migrate to FedCM page for more information.

useRenderButton

RequiredPropTypeDescription
โœ“elementHTMLElementThe element to render the button in
โœ“onSuccess(response: CredentialResponse) => voidCallback fires with credential response after successfully login
onErrorfunctionCallback fires after login failure
typestandard | iconButton type type
themeoutline | filled_blue | filled_blackButton theme
sizelarge | medium | smallButton size
textsignin_with | signup_with | continue_with | signinButton text. For example, "Sign in with Google", "Sign up with Google" or "Sign in"
shaperectangular | pill | circle | squareButton shape
logo_alignmentleft | centerGoogle logo alignment
widthnumberbutton width, in pixels
localestringIf set, then the button language is rendered
useOneTapbooleanActivate One-tap sign-up or not
promptMomentNotification(notification: PromptMomentNotification) => voidPromptMomentNotification methods and description
cancel_on_tap_outsidebooleanControls whether to cancel the prompt if the user clicks outside of the prompt
auto_selectbooleanEnables automatic selection on Google One Tap
ux_modepopup | redirectThe Sign In With Google button UX flow
login_uristringThe URL of your login endpoint
native_login_uristringThe URL of your password credential handler endpoint
native_callback(response: { id: string; password: string }) => voidThe JavaScript password credential handler function name
prompt_parent_idstringThe DOM ID of the One Tap prompt container element
noncestringA random string for ID tokens
contextsignin | signup | useThe title and words in the One Tap prompt
state_cookie_domainstringIf 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_originstring | 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_callbackfunctionOverrides the default intermediate iframe behavior when users manually close One Tap
itp_supportbooleanEnables upgraded One Tap UX on ITP browsers
hosted_domainstringIf 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
click_listenerfunctionIf set, this function will be called when the Sign in with Google button is clicked.
use_fedcm_for_promptbooleanAllow the browser to control user sign-in prompts and mediate the sign-in flow between your website and Google. Defaults to false. See Migrate to FedCM page for more information.

How to develop?

  • dev - starts dev server
  • build - generates the following bundles: CommonJS (.cjs) ESM (.mjs) and IIFE (.iife.js). The name of bundle is automatically taked from package.json name property
  • test - starts jest and runs all tests
  • test:coverage - starts jest and run all tests with code coverage report
  • lint:scripts - lint .ts files with eslint
  • prepare - script for setting up husky pre-commit hook

If you want to make changes:

  1. Fork repository
  2. Install dependencies
  3. Make changes in code and run pnpm build && pnpm pack. This command will generate .tgz file in root directory.
  4. Now you can add .tgz file to your project and test changes. Run pnpm add ~/path-to-tgz-file.tgz to add package to your project.
  5. Create Pull request with new changes.

Commit with pnpm commit!

Inspired by react-oauth

Keywords

FAQs

Last updated on 27 Feb 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with โšก๏ธ by Socket Inc