It's easy as pie to authenticate users in the front end using google sign-in for Javascript. Authenticate your back end or APIs by using the token you get from google, and authenticate requests from other back ends by signing the request with the google app token and secret
##INSTALL
Firstly, in your repository, run:
npm install --save google-back-end-auth
Then, in your code:
const googleBackendAuth = require ( 'google-back-end-auth' );
##FRONT END AUTH
To authenticate a front end request, the consumer simply needs to add the id_token they get from google to the query, like this
http://your-api.com/some-resource?id_token=<the-id-token-from-google>
##BACK END AUTH
Back end authentication works by adding a signature to the query. This signature is calculated from a combination of google tokens and request parameters (url, method, and optionally, body). It is added like this:
http://your-api.com/some-resource?sig=<signature>
Do this by calculating the signature with the sign method:
const signature = googleBackendAuth.sign ( google_client_id, google_client_secret, url, method );
or, if you're using the node request module, you can use the signRequest helper function:
const googleConfig = {
client_id: '<your-google-client-id>',
client_secret: '<your-google-client-secret>'
};
request ( googleBackendAuth.signRequest ( googleConfig, {
url: 'http://your-api.com/some-resource'
} ), callback );
NOTE: If you use this helper method with request.post, make sure to also include the method: 'post' attribute in the request object - if there's no method object, signRequest will assume it's a get request
##VERIFY THE TOKEN/SIGNATURE IN YOUR API
const googleConfig = {
client_id: '<your-google-client-id>',
client_secret: '<your-google-client-secret>',
enforce: true,
whitelist: [
/.*\.your-domain.com/, // Can match regular expressions
'some@outlier-email.com' // Or singular email addresses, as strings
] // An empty whitelist will disable id_token based authentication
};
googleBackendAuth.verifyRequest ( googleConfig, req, ( error, token ) => {
if ( error ) {
// The error will always be a string, giving an indication why authentication failed
// It will be one of the following:
// invalid token - token wasn't generated by google
// expired - user token is not recent enough
// not authentic - token might have been tampered with
// wrong app id - google client_id doesn't match one that user authenticated against
// not authorised - didn't match anything in the whitelist
// signature verification failed - back end server signature is not correct
// authentication required - no auth parameters were sent, and googleConfig.enforce
}
console.log ( token.type ) // One of:
// id_token - this will also have a userData attribute, with the user's details
// sig - back end signature authentication
// noAuth - only when !googleConfig.enforce, and no auth parameters were sent
} );