How to use google-auth-library - 10 common examples

To help you get started, we’ve selected a few google-auth-library examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github googleapis / nodejs-logging-bunyan / test / middleware / test-express.ts View on Github external
assert.strictEqual(passedOptions.length, 2);
    assert.ok(
      passedOptions.some(
        option => option!.logName === `${LOGNAME}_${APP_LOG_SUFFIX}`
      )
    );
    assert.ok(passedOptions.some(option => option!.logName === LOGNAME));
    assert.ok(passedOptions.every(option => option!.level === LEVEL));
  });

  it('should acquire the projectId and pass to makeMiddleware', async () => {
    await middleware();
    assert.strictEqual(passedProjectId, FAKE_PROJECT_ID);
  });

  [GCPEnv.APP_ENGINE, GCPEnv.CLOUD_FUNCTIONS].forEach(env => {
    it(`should not generate the request logger on ${env}`, async () => {
      authEnvironment = env;
      await middleware();
      assert.ok(passedOptions);
      assert.strictEqual(passedOptions.length, 1);
      // emitRequestLog parameter to makeChildLogger should be undefined.
      assert.strictEqual(passedEmitRequestLog, undefined);
    });
  });
});
github googleapis / google-auth-library-nodejs / system-test / fixtures / kitchen / src / index.ts View on Github external
import {GoogleAuth, JWT} from 'google-auth-library';
// uncomment the line below during development
// import {GoogleAuth} from '../../../../build/src/index';
const jwt = new JWT();
const auth = new GoogleAuth();
async function getToken() {
  const token = await jwt.getToken('token');
  const projectId = await auth.getProjectId();
  const creds = await auth.getApplicationDefault();
  return token;
}
getToken();
github actions-on-google / actions-on-google-testing-nodejs / actions-on-google.js View on Github external
createClient_(credentials) {
        const sslCreds = grpc.credentials.createSsl();
        // https://github.com/google/google-auth-library-nodejs/blob/master/ts/lib/auth/refreshclient.ts
        const refresh = new UserRefreshClient();
        refresh.fromJSON(credentials);

        const callCreds = grpc.credentials.createFromGoogleCredential(refresh);
        const combinedCreds = grpc.credentials.combineChannelCredentials(sslCreds, callCreds);

        const client = new embedded_assistant_pb.EmbeddedAssistant(this.endpoint_, combinedCreds);
        return client;
    }
github googleapis / google-auth-library-nodejs / samples / refreshAccessToken.js View on Github external
async function main() {
  try {
    // create an oAuth client to authorize the API call.  Secrets are kept in a `keys.json` file,
    // which should be downloaded from the Google Developers Console.
    const client = new OAuth2Client(
      keys.web.client_id,
      keys.web.client_secret,
      keys.web.redirect_uris[0]
    );

    client.on('tokens', tokens => {
      // You'll get a refresh token the first time the user authorizes this app.
      // You can always ask for another access_token using this long lived token.
      // Make sure to store it somewhere safe!
      if (tokens.refresh_token) {
        // store me somewhere safe!
        console.log(`Refresh Token: ${tokens.refresh_token}`);
      }
      // You'll also get new access tokens here!  These tokens expire frequently,
      // but as long as client.credentials.refresh_token is set, we can ask for
      // another one.
github google / clasp / src / auth.ts View on Github external
async function authorizeWithoutLocalhost(
  oAuth2ClientOptions: OAuth2ClientOptions,
  oAuth2ClientAuthUrlOpts: GenerateAuthUrlOpts): Promise {
  const client = new OAuth2Client({
    ...oAuth2ClientOptions,
    redirectUri: REDIRECT_URI_OOB,
  });
  const authUrl = client.generateAuthUrl(oAuth2ClientAuthUrlOpts);
  console.log(LOG.AUTHORIZE(authUrl));
  // TODO Add spinner
  const authCode = await new Promise((res, rej) => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });
    rl.question(LOG.AUTH_CODE, (code: string) => {
      if (code && code.length) {
        res(code);
      } else {
        rej('No authorization code entered.');
github googleapis / google-auth-library-nodejs / samples / headers.js View on Github external
async function main() {
  // create auth instance with custom scopes.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
  });
  const projectId = await auth.getProjectId();
  const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;

  // obtain an authenticated client
  const client = await auth.getClient();
  // Use the client to get authenticated request headers
  const headers = await client.getRequestHeaders();
  console.log('Headers:');
  console.log(headers);

  // Attach those headers to another request, and use it to call a Google API
  const res = await fetch(url, {headers});
  const data = await res.json();
  console.log('DNS Info:');
github googleapis / google-auth-library-nodejs / samples / keyfile.js View on Github external
async function main(
  // Full path to the sevice account credential
  keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS
) {
  const auth = new GoogleAuth({
    keyFile: keyFile,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
  });
  const client = await auth.getClient();
  const projectId = await auth.getProjectId();
  const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
  const res = await client.request({url});
  console.log('DNS Info:');
  console.log(res.data);
}
github googleapis / google-auth-library-nodejs / samples / jwt.js View on Github external
async function main(
  // Full path to the sevice account credential
  keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS
) {
  const keys = require(keyFile);
  const client = new JWT({
    email: keys.client_email,
    key: keys.private_key,
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
  const res = await client.request({url});
  console.log('DNS Info:');
  console.log(res.data);

  // After acquiring an access_token, you may want to check on the audience, expiration,
  // or original scopes requested.  You can do that with the `getTokenInfo` method.
  const tokenInfo = await client.getTokenInfo(client.credentials.access_token);
  console.log(tokenInfo);
}
github googleapis / google-auth-library-nodejs / samples / compute.js View on Github external
async function main() {
  const client = new Compute({
    // Specifying the serviceAccountEmail is optional. It will use the default
    // service account if one is not defined.
    serviceAccountEmail: 'some-service-account@example.com',
  });
  const projectId = await auth.getProjectId();
  const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
  const res = await client.request({url});
  console.log(res.data);
}
github googleapis / google-auth-library-nodejs / samples / compute.js View on Github external
async function main() {
  const client = new Compute({
    // Specifying the serviceAccountEmail is optional. It will use the default
    // service account if one is not defined.
    serviceAccountEmail: 'some-service-account@example.com',
  });
  const projectId = await auth.getProjectId();
  const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
  const res = await client.request({url});
  console.log(res.data);
}