1.0.4 • Published 6 months ago

express-simple-google-authn v1.0.4

Weekly downloads
-
License
ISC
Repository
-
Last release
6 months ago

šŸ’” express-simple-google-authn

Basic middleware / utility for Express which enables easy user authentication through Google Identity Services, using OAuth2 tokens. Attempts to be useful for Single Page Applications that integrate a Sign In With Google button; especially prototypes, tools and alike.\ A simple but complete supplementary frontend example is also included. Please see Usage for details.

High-level Flow

  • A Sign-in With Google button is rendered on your website, using Google Identity Services JavaScript API.
  • A user clicks on the button and goes through Google Account selection.
  • After a successful sign in, your frontend receives an ID Token from Google and forwards it to the route provided by this package.
  • The obtained short-lived ID Token is verified and a new long-lived JWT token is returned.
  • Your frontend can save the fresh JWT token and include as a header in any subsequent request which require authentication.

Disclaimer

This package is not connected to, affiliated with or endorsed by Google LLC in any way.

Prerequisites

Setting up is easy! All you need to get started is:

  • A Google Cloud Project. Create a new one if you don't have any.
  • A Web application OAuth Client ID. Create a new one if you don't have it yet: select Web application as your Application type.\ Remember to fill out the Authorised JavaScript origins section, even if you are just testing on localhost.\ FYI, the included example uses a http://localhost:8081 origin.

Usage

Backend (Express)

Using authentication in an Express server application:

const expressSimpleGoogleAuthn = require('express-simple-google-authn');

const {
    googleSignIn,
    googleUserVerify,
} = expressSimpleGoogleAuthn({
    'client_id': process.env.GOOGLE_CLIENT_ID,
    // For all available options, see the table below this sample.
});

// The provided `googleSignIn` route verifies a Google ID Token from the Authorization header and issues a new JWT token:
app.get('/google-sign-in', googleSignIn);

// Add the `googleUserVerify` middleware to any route that should require user authn:
app.get('/user', googleUserVerify, (request, response) => {
    response.json(request.google_user);
});

For the full code example and instructions on how to run the server using a single Docker command, please view example/backend/server.js in this package repository.

expressSimpleGoogleAuthn will accept the following parameters (all are optional except client_id): |name|is required?|type|default value|information| |---|---|---|---|---| |client_id|Yes|string|undefined|You can grab your Client ID from the Credentials screen In Google Cloud Console.| |hosted_domain|No|string|null|This option can be used to allow only specific G Suite users (provide your custom suffix as yourcompany.com, for example).| |request_user_prop_name|No|string|google_user|This middleware attaches the user data to request object so any subsequent handlers (like routes) can access it. Use this option if you need to change the name of the property.| |http_bad_request_code|No|integer|400|HTTP code to use for 'Bad Request' responses.| |http_unauthorized_code|No|integer|401|HTTP code to use for 'Unauthorized' responses.| |http_internal_error_code|No|integer|500|HTTP code to use for 'Internal Error' responses.| |log_exceptions|No|boolean|false|Whether to log caught and handled exceptions in console.| |jwt_lifespan_seconds|No|integer|604800|The lifespan of issued tokens in seconds. Defaults to one week.| |jwt_algo|No|string|HS256|The algorithm used to sign and verify JWT tokens. See the jsonwebtoken documentation for supported values.| |jwt_secret|No|string|buffer|object|KeyObject|crypto.randomBytes(32).toString('hex')|The secret passphrase or key used to sign JWT tokens. By default, an Ad-Hoc secret is automatically generated - please note it's not persistent and will be rotated on server restart (effectively logging the users out).|

Frontend

For the supplementary frontend example (framework agnostic), please view example/frontend/index.html provided in this package. It's a standalone application including necessary commentary and instructions on how to run.

<!-- Load Google Identity Services: -->
<!-- https://developers.google.com/identity/gsi/web/guides/overview -->
<script src='https://accounts.google.com/gsi/client'></script>

// Initialise Google Identity Services:
google.accounts.id.initialize({
    // Please remember to provide a real `client_id` (use same as for the Express middleware).
    'client_id': '???.apps.googleusercontent.com',
    // Handle Google flow completion:
    'callback': async (credentials_response) => {
        // Send the Google ID Token to our Express app:
        const id_token = credentials_response.credential;
        const response = await fetch('http://localhost:8080/google-sign-in', {
            'headers': {
                'Authorization': `Bearer ${id_token}`,
            },
        });

        // We should receive a fresh JWT token issued by our server:
        const jwt = await response.text();

        // https://pragmaticwebsecurity.com/articles/oauthoidc/localstorage-xss
        localStorage.setItem('identity', jwt);

        verifyUserCredentials();
    },
});

// Render the Google button:
// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.renderButton
const sign_in_with_google = document.getElementById('sign_in_with_google');
google.accounts.id.renderButton(sign_in_with_google, {
    'text': 'continue_with',
    'width': '280',
});

const verifyUserCredentials = async () => {
    // Authenticate the user with our stored JWT Token:
    const jwt_token = localStorage.getItem('identity');

    if (!jwt_token) {
        return;
    }

    const response  = await fetch(`http://localhost:8080/user`, {
        'headers': {
            'Authorization': `Bearer ${jwt_token}`,
        },
    });

    // If authentication was successful we'll receive decoded user information (as uid, email, name, etc.):
    const user = await response.json();
    console.log(user);
};

// Try to sign-in returning users when website loads:
verifyUserCredentials();

License

LICENSE.md

This package depends on google-auth-library (Apache 2.0 License) and jsonwebtoken (MIT License).

Contact

Please feel free to reach out if you'd like to provide feedback, contribute, or discuss your specific application:

šŸ“¬ weilandkacper@gmail.com

1.0.4

6 months ago

1.0.3

6 months ago

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago