Autenticación

Los conectores de comunidad admiten los siguientes métodos de autenticación:

  • OAuth 2.0
  • Ruta de acceso/Nombre de usuario/Contraseña
  • Ruta de acceso/clave
  • Nombre de usuario/Contraseña
  • Nombre de usuario/Token
  • Clave
  • Ninguna

Según el método que uses, debes proporcionar funciones adicionales en el conector.

En la siguiente tabla, se indican las funciones que debes definir según el tipo de autenticación de tu conector.

OAUTH2 PATH_USER_PASS
PATH_KEY
USER_PASS
USER_TOKEN
KEY
NINGUNO
getAuthType() obligatorio obligatorio obligatorio
resetAuth() obligatorio obligatorio
isAuthValid() obligatorio obligatorio
authCallback() obligatorio
get3PAuthorizationUrls() obligatorio
setCredentials() obligatorio

getAuthType()

Esta función debe mostrar el tipo de autenticación del conector.

OAUTH2

data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */
function getAuthType() {
  var cc = DataStudioApp.createCommunityConnector();
  return cc.newAuthTypeResponse()
      .setAuthType(cc.AuthType.OAUTH2)
      .build();
}

PATH_USER_PASS

/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */
function getAuthType() {
  var cc = DataStudioApp.createCommunityConnector();
  return cc.newAuthTypeResponse()
    .setAuthType(cc.AuthType.PATH_USER_PASS)
    .setHelpUrl('https://www.example.org/connector-auth-help')
    .build();
}

PATH_KEY

/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */
function getAuthType() {
  var cc = DataStudioApp.createCommunityConnector();
  return cc.newAuthTypeResponse()
    .setAuthType(cc.AuthType.PATH_KEY)
    .setHelpUrl('https://www.example.org/connector-auth-help')
    .build();
}

USER_PASS

data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */
function getAuthType() {
  var cc = DataStudioApp.createCommunityConnector();
  return cc.newAuthTypeResponse()
      .setAuthType(cc.AuthType.USER_PASS)
      .setHelpUrl('https://www.example.org/connector-auth-help')
      .build();
}

USER_TOKEN

data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */
function getAuthType() {
  var cc = DataStudioApp.createCommunityConnector();
  return cc.newAuthTypeResponse()
      .setAuthType(cc.AuthType.USER_TOKEN)
      .setHelpUrl('https://www.example.org/connector-auth-help')
      .build();
}

KEY

data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */
function getAuthType() {
  var cc = DataStudioApp.createCommunityConnector();
  return cc.newAuthTypeResponse()
      .setAuthType(cc.AuthType.KEY)
      .setHelpUrl('https://www.example.org/connector-auth-help')
      .build();
}

NINGUNO

data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */
function getAuthType() {
  var cc = DataStudioApp.createCommunityConnector();
  return cc.newAuthTypeResponse()
      .setAuthType(cc.AuthType.NONE)
      .build();
}

resetAuth()

Esta función borrará todas las credenciales almacenadas del usuario para el servicio de terceros.

OAUTH2

data-studio/auth.gs
/**
 * Resets the auth service.
 */
function resetAuth() {
  getOAuthService().reset();
}

PATH_USER_PASS

/**
 * Resets the auth service.
 */
function resetAuth() {
  var userProperties = PropertiesService.getUserProperties();
  userProperties.deleteProperty('dscc.path');
  userProperties.deleteProperty('dscc.username');
  userProperties.deleteProperty('dscc.password');
}

PATH_KEY

/**
 * Resets the auth service.
 */
function resetAuth() {
  var userProperties = PropertiesService.getUserProperties();
  userProperties.deleteProperty('dscc.path');
  userProperties.deleteProperty('dscc.key');
}

USER_PASS

data-studio/auth.gs
/**
 * Resets the auth service.
 */
function resetAuth() {
  var userProperties = PropertiesService.getUserProperties();
  userProperties.deleteProperty('dscc.username');
  userProperties.deleteProperty('dscc.password');
}

USER_TOKEN

data-studio/auth.gs
/**
 * Resets the auth service.
 */
function resetAuth() {
  var userTokenProperties = PropertiesService.getUserProperties();
  userTokenProperties.deleteProperty('dscc.username');
  userTokenProperties.deleteProperty('dscc.password');
}

KEY

data-studio/auth.gs
/**
 * Resets the auth service.
 */
function resetAuth() {
  var userProperties = PropertiesService.getUserProperties();
  userProperties.deleteProperty('dscc.key');
}

isAuthValid()

Se llama a esta función para determinar si la autenticación del servicio de terceros es válida. Si la autenticación es válida, se espera que las llamadas a getData() y getSchema() no fallen debido al acceso no autorizado. Si la autenticación no es válida, el usuario podría recibir una notificación para iniciar el flujo de autorización.

OAUTH2

data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */
function isAuthValid() {
  return getOAuthService().hasAccess();
}

PATH_USER_PASS

/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */
function isAuthValid() {
  var userProperties = PropertiesService.getUserProperties();
  var path = userProperties.getProperty('dscc.path');
  var userName = userProperties.getProperty('dscc.username');
  var password = userProperties.getProperty('dscc.password');
  // This assumes you have a validateCredentials function that
  // can validate if the path, userName and password are correct.
  return validateCredentials(path, userName, password);
}

PATH_KEY

/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */
function isAuthValid() {
  var userProperties = PropertiesService.getUserProperties();
  var path = userProperties.getProperty('dscc.path');
  var key = userProperties.getProperty('dscc.key');
  // This assumes you have a validateCredentials function that
  // can validate if the path and key are correct.
  return validateCredentials(path, key);
}

USER_PASS

data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */
function isAuthValid() {
  var userProperties = PropertiesService.getUserProperties();
  var userName = userProperties.getProperty('dscc.username');
  var password = userProperties.getProperty('dscc.password');
  // This assumes you have a validateCredentials function that
  // can validate if the userName and password are correct.
  return validateCredentials(userName, password);
}

USER_TOKEN

data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */
function isAuthValid() {
  var userProperties = PropertiesService.getUserProperties();
  var userName = userProperties.getProperty('dscc.username');
  var token = userProperties.getProperty('dscc.token');
  // This assumes you have a validateCredentials function that
  // can validate if the userName and token are correct.
  return validateCredentials(userName, token);
}

KEY

data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */
function isAuthValid() {
  var userProperties = PropertiesService.getUserProperties();
  var key = userProperties.getProperty('dscc.key');
  // This assumes you have a validateKey function that can validate
  // if the key is valid.
  return validateKey(key);
}

OAUTH2

Agrega y configura OAuth2 para la biblioteca de Apps Script

Sigue las instrucciones de configuración de la biblioteca de OAuth2 para Apps Script a fin de agregarla a tu proyecto de conector. Luego, sigue el primer paso de la guía de uso para crear un servicio de OAuth2 en tu proyecto de conector. Tu servicio de OAuth2 puede tener cualquier nombre de función válido, pero asegúrate de usar el mismo nombre y hacer referencia a este en tu código.

Por ejemplo, un servicio de OAuth2 llamado exampleService:

data-studio/auth.gs
/**
 * Returns the configured OAuth Service.
 * @return {Service} The OAuth Service
 */
function getOAuthService() {
  return OAuth2.createService('exampleService')
      .setAuthorizationBaseUrl('...')
      .setTokenUrl('...')
      .setClientId('...')
      .setClientSecret('...')
      .setPropertyStore(PropertiesService.getUserProperties())
      .setCallbackFunction('authCallback')
      .setScope('...');
};

authCallback()

Se llama a esta función para completar el flujo de OAuth 2.0. La respuesta de devolución de llamada del servicio de autenticación de terceros se proporciona como un argumento y esta función debe controlarla.

Ejemplo de cómo controlar la devolución de llamada de OAuth 2.0 con la biblioteca de OAuth2 para Apps Script:

data-studio/auth.gs
/**
 * The OAuth callback.
 * @param {object} request The request data received from the OAuth flow.
 * @return {HtmlOutput} The HTML output to show to the user.
 */
function authCallback(request) {
  var authorized = getOAuthService().handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  };
};

get3PAuthorizationUrls()

Se llama a esta función a fin de obtener la URL necesaria para iniciar el flujo de autenticación del servicio de terceros. Si isAuthValid muestra false, el usuario podrá ver la URL como un botón o vínculo para que pueda autorizar el acceso al servicio de terceros. Consulta la referencia de get3PAuthorizationUrls().

Ejemplo de cómo mostrar la URL de autorización con la biblioteca de OAuth2 para Apps Script:

data-studio/auth.gs
/**
 * Gets the 3P authorization URL.
 * @return {string} The authorization URL.
 * @see https://developers.google.com/apps-script/reference/script/authorization-info
 */
function get3PAuthorizationUrls() {
  return getOAuthService().getAuthorizationUrl();
}

USER_PASS, USER_TOKEN, KEY, PATH_USER_PASS y PATH_KEY

Lo siguiente solo es necesario para los flujos de autenticación USER_PASS, USER_TOKEN, KEY, PATH_USER_PASS y PATH_KEY.

setCredentials()

Se llama a setCredentials después de que el usuario ingresa la información de sus credenciales en la página de configuración del conector de la comunidad. Debes usar el Servicio de propiedades para guardar las credenciales por usuario con UserProperties.

PATH_USER_PASS

/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */
function setCredentials(request) {
  var creds = request.pathUserPass;
  var path = creds.path;
  var username = creds.username;
  var password = creds.password;

  // Optional
  // Check if the provided path, username and password are valid through
  // a call to your service. You would have to have a `checkForValidCreds`
  // function defined for this to work.
  var validCreds = checkForValidCreds(path, username, password);
  if (!validCreds) {
    return {
      errorCode: 'INVALID_CREDENTIALS'
    };
  }
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('dscc.path', path);
  userProperties.setProperty('dscc.username', username);
  userProperties.setProperty('dscc.password', password);
  return {
    errorCode: 'NONE'
  };
}

PATH_KEY

/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */
function setCredentials(request) {
  var creds = request.pathKey;
  var path = creds.path;
  var key = creds.key;

  // Optional
  // Check if the provided path and key are valid through
  // a call to your service. You would have to have a `checkForValidCreds`
  // function defined for this to work.
  var validCreds = checkForValidCreds(path, key);
  if (!validCreds) {
    return {
      errorCode: 'INVALID_CREDENTIALS'
    };
  }
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('dscc.path', path);
  userProperties.setProperty('dscc.key', key);
  return {
    errorCode: 'NONE'
  };
}

USER_PASS

data-studio/auth.gs
/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */
function setCredentials(request) {
  var creds = request.userPass;
  var username = creds.username;
  var password = creds.password;

  // Optional
  // Check if the provided username and password are valid through a
  // call to your service. You would have to have a `checkForValidCreds`
  // function defined for this to work.
  var validCreds = checkForValidCreds(username, password);
  if (!validCreds) {
    return {
      errorCode: 'INVALID_CREDENTIALS'
    };
  }
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('dscc.username', username);
  userProperties.setProperty('dscc.password', password);
  return {
    errorCode: 'NONE'
  };
}

USER_TOKEN

data-studio/auth.gs
/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */
function setCredentials(request) {
  var creds = request.userToken;
  var username = creds.username;
  var token = creds.token;

  // Optional
  // Check if the provided username and token are valid through a
  // call to your service. You would have to have a `checkForValidCreds`
  // function defined for this to work.
  var validCreds = checkForValidCreds(username, token);
  if (!validCreds) {
    return {
      errorCode: 'INVALID_CREDENTIALS'
    };
  }
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('dscc.username', username);
  userProperties.setProperty('dscc.token', token);
  return {
    errorCode: 'NONE'
  };
}

KEY

data-studio/auth.gs
/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */
function setCredentials(request) {
  var key = request.key;

  // Optional
  // Check if the provided key is valid through a call to your service.
  // You would have to have a `checkForValidKey` function defined for
  // this to work.
  var validKey = checkForValidKey(key);
  if (!validKey) {
    return {
      errorCode: 'INVALID_CREDENTIALS'
    };
  }
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('dscc.key', key);
  return {
    errorCode: 'NONE'
  };
}