All Projects → joegasewicz → react-google-oauth2.0

joegasewicz / react-google-oauth2.0

Licence: MIT license
React frontend login with OAuth 2.0 & integrates a Rest API backend.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
Makefile
30231 projects

Projects that are alternatives of or similar to react-google-oauth2.0

Httpie Oauth
OAuth plugin for HTTPie
Stars: ✭ 78 (+457.14%)
Mutual labels:  oauth, auth
React Native Instagram Login
a react native instagram login component (support android & ios). Pull requests are welcome!
Stars: ✭ 139 (+892.86%)
Mutual labels:  oauth, auth
Vue Authenticate
Simple Vue.js authentication library
Stars: ✭ 1,350 (+9542.86%)
Mutual labels:  oauth, auth
Retroauth
A library build on top of retrofit, for simple handling of authenticated requests
Stars: ✭ 405 (+2792.86%)
Mutual labels:  oauth, oauth2-client
casdoor-go-sdk
Go client SDK for Casdoor
Stars: ✭ 37 (+164.29%)
Mutual labels:  oauth, auth
Idtoken Verifier
Lightweight RSA JWT verification
Stars: ✭ 52 (+271.43%)
Mutual labels:  oauth, auth
Fosite
Extensible security first OAuth 2.0 and OpenID Connect SDK for Go.
Stars: ✭ 1,738 (+12314.29%)
Mutual labels:  oauth, auth
Authl
A library for managing federated identity
Stars: ✭ 20 (+42.86%)
Mutual labels:  oauth, oauth2-client
Twitch4j
Modular Async/Sync/Reactive Twitch API Client / IRC Client
Stars: ✭ 209 (+1392.86%)
Mutual labels:  oauth, auth
Oauthlib
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic
Stars: ✭ 2,323 (+16492.86%)
Mutual labels:  oauth, jwt-authentication
Angular Token
🔑 Token based authentication service for Angular with interceptor and multi-user support. Works best with devise token auth for Rails. Example:
Stars: ✭ 376 (+2585.71%)
Mutual labels:  oauth, auth
express-mongo-jwt-boilerplate
Express Mongo JsonWebToken boilerplate
Stars: ✭ 100 (+614.29%)
Mutual labels:  auth, jwt-authentication
Aspnetcore Webapi Course
Professional REST API design with ASP.NET Core 3.1 WebAPI
Stars: ✭ 323 (+2207.14%)
Mutual labels:  oauth, jwt-authentication
Google Auth Library Nodejs
🔑 Google Auth Library for Node.js
Stars: ✭ 1,094 (+7714.29%)
Mutual labels:  oauth, oauth2-client
Oauthswift
Swift based OAuth library for iOS
Stars: ✭ 2,949 (+20964.29%)
Mutual labels:  oauth, oauth2-client
Flask Oauthlib
YOU SHOULD USE https://github.com/lepture/authlib
Stars: ✭ 1,429 (+10107.14%)
Mutual labels:  oauth, oauth2-client
yii-auth-client
Yii Framework external authentication via OAuth and OpenID Extension
Stars: ✭ 20 (+42.86%)
Mutual labels:  oauth, auth
supabase-ui-svelte
Supabase authentication UI for Svelte
Stars: ✭ 83 (+492.86%)
Mutual labels:  oauth, auth
Monkey
Monkey is an unofficial GitHub client for iOS,to show the rank of coders and repositories.
Stars: ✭ 1,765 (+12507.14%)
Mutual labels:  oauth, oauth2-client
sign-in-with-ethereum
Minimal example of sign in with Ethereum. Compatible with web3 browsers.
Stars: ✭ 25 (+78.57%)
Mutual labels:  oauth, auth

Build & Test Node.js Package GitHub license GitHub issues npm

React Google OAuth 2.0

Easily add Google OAuth 2.0 Single Sign On to a React app & let your server handle your access & refresh tokens. This library will work directly with Flask JWT Router & provide Google OAuth 2.0 integration out of the box with minimal setup.

Docs: https://joegasewicz.github.io/react-google-oauth2.0/

Install

npm install react-google-oauth2

Quick Start

import * as React from "react";
import * as ReactDOM from "react-dom";

import {
    GoogleButton,
    IAuthorizationOptions,
    isLoggedIn,
    createOAuthHeaders,
    logOutOAuthUser,
    GoogleAuth,
} from "react-google-oauth2";

function App(props: any) {

    const options: IAuthorizationOptions = {
        clientId: (process.env.CLIENT_ID as string),
        redirectUri: "http://localhost:3000/react-google-Oauth2.0/dist/index.html",
        scopes: ["openid", "profile", "email"],
        includeGrantedScopes: true,
        accessType: "offline",
    };

    return (
        <>
          <GoogleButton
              placeholder="demo/search.png" // Optional
              options={options}
              apiUrl="http://localhost:5000/google_login"
              defaultStyle={true} // Optional
          />
        </>
    );
}

ReactDOM.render(
    </App>,
    document.getElementById("main"),
);

GoogleAuth Provider & GoogleAuthConsumer

Get notified when a user has logged in successfully by wrapping the GoogleButton component within the GoogleAuth provider. You can then use the GoogleAuthConsumer to redirect to your authorized routes when {isAuthenticated} is true. For example:

import {
    GoogleAuth,
    GoogleButton,
    GoogleAuthConsumer,
    IOAuthState,
} from "react-google-oauth2";

<GoogleAuth>
    <GoogleAuthConsumer>
        {({responseState, isAuthenticated}: IOAuthState) => {
            if (!isAuthenticated) {
            return <GoogleButton
                  placeholder="demo/search.png" // Optional
                  options={options}
                  apiUrl="http://localhost:5000/google_login"
                  defaultStyle={true} // Optional
                  displayErrors={true}>Sign in with google</GoogleButton>;
            } else {
                if (responseState.accessToken) { // You can also use isLoggedIn()
                    // Now send a request to your server using  createOAuthHeaders() function
                    fetch(url, {
                        headers: createOAuthHeaders(),
                    })
                    .then(data => console.log("Horay We're logged in!"))
                    .catch(err => console.error("Just because you have a gmail account doesn't mean you have access!"))
                }
            }
        }}
    </GoogleAuthConsumer>
</GoogleAuth>

OAuth2.0 Helper Functions

Check if OAuth2.0 user is logged in

if(isLoggedIn()) { // returns true is accessToken exists in LocalStorage
    // user logged code...
}

Creat OAuth2.0 Server Headers

// Using Fetch API example:
fetch(url, {
    headers: createOAuthHeaders(),
});

Log out OAuth2.0 users

logOutOAuthUser() // removes the accessToken from LocalStorage

Your Rest API endpoint details

The GoogleButton component will make the following request to your api:

POST options = {body: { code: <code>, scope: <scope> }} URL = `apiUrl`

Update prompts

If for example your user updates their email in your app & you redirect them to the login again, Google will by default skip the Google email select screen & log you in with your existing credentials. To stop this happening you can use the following function:

setPrompt("select_account");

Below is an example with setPrompt function resetting your

const sso_options: IAuthorizationOptions = {
    clientId: "<CLIENT_ID>",
    redirectUri: `http://localhost:3000/login`,
    scopes: ["openid", "profile", "email"],
    accessType: "offline",
};

Then in your login component it could look like this:

<GoogleAuth>
    <GoogleAuthConsumer>
        {({ responseState, isAuthenticated, setPrompt }: IOAuthState) => {
                if (!isAuthenticated) {
                    // Here we are using Lodash fp to get our prompt value
                    // passed from the React Router location API e.g:
                    // history.push({ pathname: "/login", { prompt: "select_account" });
                    const prompt = fp.get("state.prompt", location);
                    if (prompt) {
                        // this will now set sso_option.prompt = "select_account"
                        // for this login attempt, then the auto login flow will
                        // continue as normal
                        setPrompt(prompt);
                    }
                    return <StyledGoogleButton>
                        <GoogleButton
                            defaultStyle={false}
                            options={sso_option}
                            apiUrl="http://localhost:3000/users/login"
                        >Login</GoogleButton>
                    </StyledGoogleButton>;
                } else {
                    if (responseState?.accessToken && isOAuthLoggedIn()) {
                        updateShouldFetch(isOAuthLoggedIn());
                        if (staff) {
                           return <Redirect to="/staff"/>;
                        } else {
                            return null;
                        }
                    }
                    return null;
                }
        }}
    </GoogleAuthConsumer>
</GoogleAuth>

Access tokens for e2e tests

To test your React app with an e2e testing framework such as cypressIO you can use the exchangeToken function.

The exchangeToken function fetches the new access token and sets it into local storage and also returns the access token.

Example to fetch and set an access token in local storage

 exchangeToken(CLIENT_ID, REFRESH_TOKEN, CLIENT_SECRET)
 .then(accessToken => {
      console.log(accessToken) // your access token...
  });

If you require an access token to run your e2e tests then exchangeToken will set and return a new access token.

import { exchangeToken,getAccessToken, createOAuthHeaders } from "react-google-oauth2";

describe("test something...",  () => {
   Cypress.Commands.add("loginSSO",  (overrides = {}) => {
       Cypress.log({
           "name": "loginSSO",
       });
       // Fetche an access token before each tests only if there isn't one present
       if(!getAccessToken()) { 
           exchangeToken(CLIENT_ID, REFRESH_TOKEN, CLIENT_SECRET)
               .then(accessToken => {
                   cy.request({
                       method: 'GET',
                       url: `${API_URL}/staff`,
                       headers: createOAuthHeaders(),
                   });
               });
       }
   });
   beforeEach(() => {
       cy.loginSSO(); 
   });
});

Flask-JWT-Router

If you are using Flask as your REST api framework then this library is designed to work directly with flask-jwt-router. See Flask JWT Router for more details.

Styling

To Style the <button> element with CSS, use google-oauth-btn selector. For example:

.google-oauth-btn {
    color: red;
    background-color: lime;
}

(you can also pass your css selectors directly with Reacts' className prop)

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].