身份验证

支持以下五种身份验证方法:

  • OAuth 2.0
  • 用户名/密码
  • 用户名/令牌
  • 密钥

您还必须在连接器中提供其他函数,具体取决于您当前所用的方法。

下表显示了根据连接器的身份验证类型,您必须定义的函数。

OAUTH2 USER_PASS/USER_TOKEN/KEY
getAuthType() 必需 必需 必需
resetAuth() 必需 必需
isAuthValid() 必需 必需
authCallback() 必需
get3PAuthorizationUrls() 必需
setCredentials() 必需

getAuthType()

此函数应返回连接器的身份验证类型。

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();
    }

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();
    }

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()

此函数将清除为第三方服务用户存储的所有凭据。

OAUTH2

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

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 user_tokenProperties = PropertiesService.getUserProperties();
      user_tokenProperties.deleteProperty('dscc.username');
      user_tokenProperties.deleteProperty('dscc.password');
    }

KEY

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

isAuthValid()

可调用此函数来确定对第三方服务进行的身份验证是否有效。如果身份验证有效,则对 getData()getSchema() 的调用不应该因未经授权的访问而失败。如果身份验证无效,则用户可能会收到开始授权流程的通知。

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();
    }

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

添加和设置适用于 Apps 脚本的 OAuth2 库

按照适用于 Apps 脚本的 OAuth2 库的设置说明,将其添加到您的连接器项目。然后按照使用指南的第一步,在连接器项目中创建 OAuth2 服务。OAuth2 服务的名称可以是任何有效的函数名称,但请确保在代码中引用 OAuth2 服务时使用相同的名称。

例如,名为 exampleService 的 OAuth2 服务:

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()

可调用此函数来完成 OAuth 2.0 流程。来自第三方身份验证服务的回调响应作为参数提供,并且应由此函数处理。

使用适用于 Apps 脚本的 OAuth2 库处理 OAuth 2.0 回调的示例:

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()

可调用此函数来获取针对第三方服务启动身份验证流程所需的网址。如果 isAuthValid 返回 false,则返回的网址将以按钮或链接的形式向用户显示,以便他们可以向第三方服务授予访问权限。请参阅 get3PAuthorizationUrls() 参考。

使用适用于 Apps 脚本的 OAuth2 库返回授权网址的示例:

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_PASSUSER_TOKENKEY

只有 USER_PASSUSER_TOKENKEY 身份验证流程需要以下函数。

setCredentials()

用户在社区连接器配置页面上输入其凭据信息后,系统将调用 setCredentials。您应该使用属性服务,以便通过 UserProperties 按用户保存凭据。

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'
      };
    }