使用 OAuth 进行 Looker API 身份验证

Looker 使用 OAuth 让 OAuth 客户端应用向 Looker API 进行身份验证,而无需向运行 OAuth 客户端应用的浏览器公开客户端 ID 和客户端密钥。

使用 OAuth 的 Web 应用必须满足以下要求:

  • 只有 Looker API 4.0 支持使用 OAuth 进行身份验证。
  • OAuth 客户端应用必须先使用 API 向 Looker 注册,然后应用的用户才能向 Looker 进行身份验证。
  • 客户端应用必须使用 HTTPS 向 Looker API 发出所有请求。想要使用浏览器提供的 SubtleCrypto API 的客户端应用必须托管在 HTTPS 网站上。

Looker API CORS 支持

Looker API 支持使用跨域资源共享 (CORS) 协议在浏览器中和跨域调用。Looker CORS 支持具有以下要求:

  • 只有嵌入式网域许可清单中列出的来源才能使用 CORS 调用 API。

  • 只有从 OAuth 或通过调用 /login API 端点获取的访问令牌,才能用于通过 CORS 调用 Looker API。

OAuth 身份验证概览

OAuth 身份验证流程概览如下:

  1. 向 Looker 实例注册 OAuth 客户端应用。
  2. 将 OAuth 客户端应用的来源添加到嵌入式网域许可清单中,以便进行代码交换 API 调用和任何后续 CORS API 调用。

  3. 当 OAuth 客户端应用尝试对用户进行身份验证时,将浏览器网址重定向到 Looker 界面主机名(而非 Looker API 主机名)上的 /auth 端点。例如 https://instance_name.looker.com。

  4. 如果用户成功通过身份验证并登录 Looker,Looker 会立即向 OAuth 客户端应用返回 OAuth 重定向。如果用户尚未在设备和浏览器上登录 Looker,系统会显示 Looker 登录界面,并提示用户使用其常规身份验证协议登录其 Looker 用户账号。

  5. 使用 OAuth 重定向中返回的授权代码,您的 OAuth 客户端应用接下来应调用 Looker API 主机名上的 /token 端点,例如 https://instance_name.looker.com:19999。API 主机名可能与 Looker 界面主机名相同,也可能不同。/token 端点仅存在于 Looker API 主机上,而 /auth 端点仅存在于 Looker 界面主机上。

  6. 如果传递给 /token 端点的授权代码有效,Looker 会返回一个 API access_token,该 API 已启用,可接收来自 OAuth 客户端应用网域的 CORS API 请求。

注册 OAuth 客户端应用

每个尝试使用 OAuth 向 Looker API 进行身份验证的 OAuth 客户端应用都必须先向 Looker 实例注册,然后 Looker 才会授权访问。

Looker 管理员可以直接在 Looker 管理面板中的管理 OAuth 客户端页面(管理 > 身份验证 > 管理 OAuth 客户端)上注册和管理自定义 OAuth 客户端应用。管理员可以通过此界面执行以下任务:

  • 为应用配置一个或多个已获授权的重定向 URI,以支持多个环境和端口。
  • 仅限特定 Looker 用户群组的成员访问授权(仅限群组 ID)。
  • 查看、修改、启用、停用或删除已注册的自定义应用。

如需了解在管理面板中注册自定义客户端的分步说明,请参阅管理设置 - 管理 OAuth 客户端文档页面。

使用 API 进行程序化注册

或者,管理员也可以通过直接调用注册 OAuth 应用端点或在 Looker API Explorer 中运行该端点,以编程方式注册 OAuth 客户端应用。这些参数包括:

  • client_guid:应用的唯一字符串 ID(不能以 com.looker. 开头)。
  • redirect_uris:一组已获授权的回调 URI,应用将在这些 URI 接收 OAuth 重定向和授权代码。
  • display_name:向用户显示的应用名称。
  • description:OAuth 客户端应用的说明。
  • group_id(可选):要限制访问权限的 Looker 群组的数字 ID。

使用 OAuth 执行用户登录

  1. 将用户引导至界面主机上的 /auth 端点。例如:

    async function oauth_login() {
      const code_verifier = secure_random(32)
      const code_challenge = await sha256_hash(code_verifier)
      const params = {
        response_type: 'code',
        client_id: '123456',
        redirect_uri: 'https://mywebapp.com:3000/authenticated',
        scope: 'cors_api',
        state: '1235813',
        code_challenge_method: 'S256',
        code_challenge: code_challenge,
      }
      const url = `${base_url}?${new URLSearchParams(params).toString()}` // Replace base_url with your full Looker instance's UI host URL, plus the `/auth` endpoint.
      log(url)
    
      // Stash the code verifier we created in sessionStorage, which
      // will survive page loads caused by login redirects
      // The code verifier value is needed after the login redirect
      // to redeem the auth_code received for an access_token
      //
      sessionStorage.setItem('code_verifier', code_verifier)
    
      document.location = url
    }
    
    function array_to_hex(array) {
      return Array.from(array).map(b => b.toString(16).padStart(2,'0')).join('')
    }
    
    function secure_random(byte_count) {
      const array = new Uint8Array(byte_count);
      crypto.getRandomValues(array);
      return array_to_hex(array)
    }
    
    async function sha256_hash(message) {
      const msgUint8 = new TextEncoder().encode(message)
      const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8)
      return base64.urlEncode(hashBuffer))  // Refers to the implementation of base64.encode stored at https://gist.github.com/jhurliman/1250118
    }
    

    Looker 将尝试使用为 Looker 实例配置的身份验证系统对用户进行身份验证。

    • 如果用户已在当前浏览器中登录 Looker(即存在有效的登录 Cookie 状态),则系统不会提示用户输入登录凭证。
    • 如果这是该用户首次使用此 OAuth 客户端应用登录,Looker 将显示一个披露和确认页面,供用户确认和接受。系统会显示注册应用时使用的 description 参数中的文本。说明应指明应用打算如何使用用户的 Looker 账号。用户点击接受后,页面将重定向到应用 redirect_uri。
    • 如果用户已在当前浏览器中登录 Looker,并且已确认披露声明页面,则 OAuth 登录会立即完成,不会出现视觉中断。
  2. Looker API 会向 OAuth 客户端应用返回 OAuth 重定向。保存 URI 参数中列出的授权代码。以下是 OAuth 重定向 URI 示例:

    https://mywebapp.com:3000/authenticated?&code=asdfasdfassdf&state=...
    

    授权代码显示在 URI 中的 &code= 后面。在此示例中,授权代码为 asdfasdfassdf。

  3. 向 Looker API 中的 /token 端点发出 Web 请求,并传递授权代码和应用信息。例如:

    async function redeem_auth_code(response_str) {
      const params = new URLSearchParams(response_str)
      const auth_code = params.get('code')
    
      if (!auth_code) {
        log('ERROR: No authorization code in response')
        return
      }
      log(`auth code received: ${auth_code}`)
      log(`state: ${params.get('state')}`)
    
      const code_verifier = sessionStorage.getItem('code_verifier')
      if (!code_verifier) {
        log('ERROR: Missing code_verifier in session storage')
        return
      }
      sessionStorage.removeItem('code_verifier')
      const response = await
      fetch('https://mycompany.looker.com:19999/api/token', {  // This is the URL of your Looker instance's API web service
        method: 'POST',
        mode: 'cors',    // This line is required so that the browser will attempt a CORS request.
        body: stringify({
          grant_type: 'authorization_code',
          client_id: '123456',
          redirect_uri: 'https://mywebapp.com:3000/authenticated',
          code: auth_code,
          code_verifier: code_verifier,
        }),
        headers: {
          'x-looker-appid': 'Web App Auth & CORS API Demo', // This header is optional.
          'Content-Type': 'application/json;charset=UTF-8'  // This header is required.
        },
      }).catch((error) => {
        log(`Error: ${error.message}`)
      })
    
      const info = await response.json()
      log(`/api/token response: ${stringify(info)}`)
    
      // Store the access_token and other info,
      // which in this example is done in sessionStorage
    
      const expires_at = new Date(Date.now() + (info.expires_in * 1000))
      info.expires_at = expires_at
      log(`Access token expires at ${expires_at.toLocaleTimeString()} local time.`)
      sessionStorage.setItem('access_info', stringify(info))
      access_info = info
    }
    

    成功的响应会向 OAuth 客户端应用提供 API access_token。响应中还会包含一个 refresh_token,您稍后可以使用它在没有用户互动的情况下获取新的 access_token。refresh_token 的有效期为一个月。安全地存储 refresh_token。

    Looker 管理员可以随时撤消此系统中的所有令牌。