What is gtoken?
The gtoken npm package is designed to handle the acquisition and management of Google OAuth2 tokens. It simplifies the process of authenticating with Google APIs by managing the token generation, refresh, and validation processes.
What are gtoken's main functionalities?
Generate Access Token
This feature allows users to generate an access token by providing a key file and the required scopes. The token can then be used to authenticate requests to Google APIs.
const { GoogleToken } = require('gtoken');
const gtoken = new GoogleToken({
keyFile: 'path/to/keyfile.json',
scope: ['https://www.googleapis.com/auth/drive']
});
gtoken.getToken().then(token => {
console.log(token);
}).catch(err => {
console.error(err);
});
Refresh Token
This feature allows users to refresh their existing token when it expires. The refreshed token ensures continued access without needing to re-authenticate.
const { GoogleToken } = require('gtoken');
const gtoken = new GoogleToken({
keyFile: 'path/to/keyfile.json',
scope: ['https://www.googleapis.com/auth/drive'],
token: existingToken
});
gtoken.refreshToken().then(newToken => {
console.log(newToken);
}).catch(err => {
console.error(err);
});
Other packages similar to gtoken
google-auth-library
Similar to gtoken, google-auth-library is a comprehensive library for Google authentication, supporting OAuth2, service accounts, and other authentication methods. It offers more extensive features compared to gtoken, including support for various environments and additional Google authentication flows.
oauth2-client-js
This package provides mechanisms for implementing OAuth2 clients. While it is not specific to Google, it can be used for Google OAuth2 authentication. It is more generic compared to gtoken, which is specifically tailored for Google token management.
Node.js Google Authentication Service Account Tokens
This is a low level utility library used to interact with Google Authentication services. In most cases, you probably want to use the google-auth-library instead.
Installation
npm install gtoken
Usage
Use with a .pem
or .p12
key file:
const { GoogleToken } = require('gtoken');
const gtoken = new GoogleToken({
keyFile: 'path/to/key.pem',
email: 'my_service_account_email@developer.gserviceaccount.com',
scope: ['https://scope1', 'https://scope2']
});
gtoken.getToken((err, tokens) => {
if (err) {
console.log(err);
return;
}
console.log(tokens);
});
You can also use the async/await style API:
const tokens = await gtoken.getToken()
console.log(tokens);
Or use promises:
gtoken.getToken()
.then(tokens => {
console.log(tokens)
})
.catch(console.error);
Use with a service account .json
key file:
const { GoogleToken } = require('gtoken');
const gtoken = new GoogleToken({
keyFile: 'path/to/key.json',
scope: ['https://scope1', 'https://scope2']
});
gtoken.getToken((err, tokens) => {
if (err) {
console.log(err);
return;
}
console.log(tokens);
});
Pass the private key as a string directly:
const key = '-----BEGIN RSA PRIVATE KEY-----\nXXXXXXXXXXX...';
const { GoogleToken } = require('gtoken');
const gtoken = new GoogleToken({
email: 'my_service_account_email@developer.gserviceaccount.com',
scope: ['https://scope1', 'https://scope2'],
key: key
});
Options
Various options that can be set when creating initializing the gtoken
object.
options.email or options.iss
: The service account email address.options.scope
: An array of scope strings or space-delimited string of scopes.options.sub
: The email address of the user requesting delegated access.options.keyFile
: The filename of .json
key, .pem
key or .p12
key.options.key
: The raw RSA private key value, in place of using options.keyFile
.
.getToken(callback)
Returns the cached tokens or requests a new one and returns it.
gtoken.getToken((err, token) => {
console.log(err || token);
});
.getCredentials('path/to/key.json')
Given a keyfile, returns the key and (if available) the client email.
const creds = await gtoken.getCredentials('path/to/key.json');
Properties
Various properties set on the gtoken object after call to .getToken()
.
gtoken.idToken
: The OIDC token returned (if any).gtoken.accessToken
: The access token.gtoken.expiresAt
: The expiry date as milliseconds since 1970/01/01gtoken.key
: The raw key value.gtoken.rawToken
: Most recent raw token data received from Google.
.hasExpired()
Returns true if the token has expired, or token does not exist.
const tokens = await gtoken.getToken();
gtoken.hasExpired();
.revokeToken()
Revoke the token if set.
await gtoken.revokeToken();
console.log('Token revoked!');
Downloading your private .p12
key from Google
- Open the Google Developer Console.
- Open your project and under "APIs & auth", click Credentials.
- Generate a new
.p12
key and download it into your project.
Converting your .p12
key to a .pem
key
You can just specify your .p12
file (with .p12
extension) as the keyFile
and it will automatically be converted to a .pem
on the fly, however this results in a slight performance hit. If you'd like to convert to a .pem
for use later, use OpenSSL if you have it installed.
$ openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem
Don't forget, the passphrase when converting these files is the string 'notasecret'
License
MIT
4.0.0 (2019-07-09)
⚠ BREAKING CHANGES
- This commit creates multiple breaking changes. The
getToken()
method previously returned Promise<string>
, where the string was the
access_token
returned from the response. However, the oauth2
endpoint could
return a variety of other fields, such as an id_token
in special cases.
const token = await getToken();
// old response: 'some.access.token'
// new response: { access_token: 'some.access.token'}
To further support this change, the GoogleToken
class no longer exposes
a token
variable. It now exposes rawToken
, accessToken
, and idToken
fields which can be used to access the relevant values returned in the
response.
Bug Fixes