建立一个 Supabase 集成
This guide steps through building a Supabase Integration using OAuth2 and the management API, allowing you to manage users' organizations and projects on their behalf.
使用 OAuth2.0,你可以获取一个访问令牌和刷新令牌,从而代表用户让你的应用完全访问 管理 API。
🌐 Using OAuth2.0 you can retrieve an access and refresh token that grant your application full access to the Management API on behalf of the user.
创建一个 OAuth 应用 #
🌐 Create an OAuth app
- 在你们组织的设置中,导航到 OAuth 应用 标签。
- 在页面的右上角,点击 添加应用。
- 填写必要的详细信息,然后点击 确认。
显示一个“连接 Supabase”按钮 #
🌐 Show a "Connect Supabase" button
在你的用户界面中,添加一个“连接 Supabase”按钮来启动 OAuth 流程。按照我们 品牌资源 中的设计指南进行操作。
🌐 In your user interface, add a "Connect Supabase" button to kick off the OAuth flow. Follow the design guidelines outlined in our brand assets.
实现 OAuth 2.0 流程 #
🌐 Implementing the OAuth 2.0 flow
一旦你在 Supabase 上发布了你的 OAuth 应用,你就可以使用 OAuth 2.0 协议从 Supabase 用户那里获取授权,以管理他们的组织和项目。
🌐 Once you've published your OAuth App on Supabase, you can use the OAuth 2.0 protocol get authorization from Supabase users to manage their organizations and projects.
你可以使用你喜欢的 OAuth2 客户端,或者按照下面的步骤操作。你可以在我们的 GitHub 上看到使用 Supabase Edge Functions 的 TypeScript 示例实现 在这里。
🌐 You can use your preferred OAuth2 client or follow the steps below. You can see an example implementation in TypeScript using Supabase Edge Functions on our GitHub.
正在重定向到授权网址 #
🌐 Redirecting to the authorize URL
在你应用的界面中,将用户重定向到 https://api.supabase.com/v1/oauth/authorize。确保包含所有必需的查询参数,例如:
🌐 Within your app's UI, redirect the user to https://api.supabase.com/v1/oauth/authorize. Make sure to include all required query parameters such as:
client_id:你在上面创建应用时得到的客户端ID。redirect_uri:用户同意后,Supabase 会把他们重定向到的 URL。response_type:把这个设置为code。state:关于你的应用状态的信息。注意,redirect_uri和state加起来的大小不能超过 4KB。organization_slug:你想连接的组织的标识符。这是可选的,但如果提供了,它会为用户预先选择该组织。- [推荐] PKCE:我们强烈建议使用 PKCE 流程来提高安全性。在引导用户到授权端点之前,先生成一个随机值。这个值叫做 code verifier。用 SHA256 对它进行哈希处理,并作为
code_challenge参数传入,同时把code_challenge_method设置为S256。在下一步,你需要提供这个 code verifier 才能获取第一个访问令牌和刷新令牌。 - [已弃用]
scope:在创建你的 OAuth 应用时配置作用域。更多详情请阅读文档。
1router.get('/connect-supabase/login', async (ctx) => {2 // Construct the URL for the authorization redirect and get a PKCE codeVerifier.3 const { uri, codeVerifier } = await oauth2Client.code.getAuthorizationUri()4 console.log(uri.toString())5 // console.log: https://api.supabase.com/v1/oauth/authorize?response_type=code&client_id=7673bde9-be72-4d75-bd5e-b0dba2c49b38&redirect_uri=http%3A%2F%2Flocalhost%3A54321%2Ffunctions%2Fv1%2Fconnect-supabase%2Foauth2%2Fcallback&scope=all&code_challenge=jk06R69S1bH9dD4td8mS5kAEFmEbMP5P0YrmGNAUVE0&code_challenge_method=S25667 // Store the codeVerifier in the user session (cookie).8 ctx.state.session.flash('codeVerifier', codeVerifier)910 // Redirect the user to the authorization endpoint.11 ctx.response.redirect(uri)12})在 GitHub 上查看完整示例。
🌐 Find the full example on GitHub.
处理回调 #
🌐 Handling the callback
一旦用户同意为你的 OAuth 应用提供 API 访问权限,Supabase 就会把用户重定向到上一步提供的 redirect_uri。URL 会包含这些查询参数:
🌐 Once the user consents to providing API access to your OAuth App, Supabase will redirect the user to the redirect_uri provided in the previous step. The URL will contain these query parameters:
code:你应该用这个授权码跟 Supabase 交换,以获取访问令牌和刷新令牌。state:你在上一步提供的值,用来帮助你将请求与用户关联。这里返回的state属性应该与之前你发送的state对比。
通过调用 POST https://api.supabase.com/v1/oauth/token 并使用以下查询参数作为内容类型 application/x-www-form-urlencoded,将授权码兑换为访问令牌和刷新令牌:
🌐 Exchange the authorization code for an access and refresh token by calling POST https://api.supabase.com/v1/oauth/token with the following query parameters as content-type application/x-www-form-urlencoded:
grant_type:值authorization_code。code:上一步返回的code。redirect_uri:这个必须和第一步用的 URL 完全一样。- (推荐)
code_verifier:如果你在第一步使用了 PKCE 流程,请将代码验证器作为code_verifier包含。
如果你的应用需要支持动态生成的重定向 URL,请查看下面的 处理动态重定向 URL 部分。
🌐 If your application need to support dynamically generated Redirect URLs, check out Handling Dynamic Redirect URLs section below.
根据 OAuth2 规范,提供客户端 ID 和客户端密钥作为基础认证头:
🌐 As per OAuth2 spec, provide the client id and client secret as basic auth header:
client_id:用于识别你 OAuth 应用的唯一客户端 ID。client_secret:用于验证你的 OAuth 应用到 Supabase 的秘密。
1router.get('/connect-supabase/oauth2/callback', async (ctx) => {2 // Make sure the codeVerifier is present for the user's session.3 const codeVerifier = ctx.state.session.get('codeVerifier') as string4 if (!codeVerifier) throw new Error('No codeVerifier!')56 // Exchange the authorization code for an access token.7 const tokens = await fetch(config.tokenUri, {8 method: 'POST',9 headers: {10 'Content-Type': 'application/x-www-form-urlencoded',11 Accept: 'application/json',12 Authorization: `Basic ${btoa(`${config.clientId}:${config.clientSecret}`)}`,13 },14 body: new URLSearchParams({15 grant_type: 'authorization_code',16 code: ctx.request.url.searchParams.get('code') || '',17 redirect_uri: config.redirectUri,18 code_verifier: codeVerifier,19 }),20 }).then((res) => res.json())21 console.log('tokens', tokens)2223 // Store the tokens in your DB for future use.2425 ctx.response.body = 'Success'26})在 GitHub 上查看完整示例。
🌐 Find the full example on GitHub.
刷新访问令牌 #
🌐 Refreshing an access token
你可以使用 POST /v1/oauth/token 接口通过上一部分末尾返回的刷新令牌来刷新访问令牌。
🌐 You can use the POST /v1/oauth/token endpoint to refresh an access token using the refresh token returned at the end of the previous section.
如果用户撤销了对你应用的访问权限,你将无法刷新令牌。此外,访问令牌将停止工作。确保在调用任何 Supabase API 时处理 HTTP 未授权错误。
🌐 If the user has revoked access to your application, you will not be able to refresh a token. Furthermore, access tokens will stop working. Make sure you handle HTTP Unauthorized errors when calling any Supabase API.
调用管理 API #
🌐 Calling the Management API
请参考 管理 API 文档 了解更多关于管理 API 的身份验证信息。
🌐 Refer to the Management API reference to learn more about authentication with the Management API.
使用 JavaScript(TypeScript)SDK #
🌐 Use the JavaScript (TypeScript) SDK
为了方便,在使用 JavaScript/TypeScript 时,你可以使用 supabase-management-js 库。
🌐 For convenience, when working with JavaScript/TypeScript, you can use the supabase-management-js library.
1import { SupabaseManagementAPI } from 'supabase-management-js'23const client = new SupabaseManagementAPI({ accessToken: '<access token>' })集成建议 #
🌐 Integration recommendations
有几个常见的模式你可以考虑加到你的集成里,这样可以让用户体验更棒。
🌐 There are a couple common patterns you can consider adding to your integration that can facilitate a great user experience.
把 API 密钥存到环境变量里 #
🌐 Store API keys in env variables
一些集成,例如像 Cloudflare Workers 提供了便捷的 API URL 和 API 密钥访问,让用户可以加快开发速度。
🌐 Some integrations, e.g. like Cloudflare Workers provide convenient access to the API URL and API keys to allow user to speed up development.
使用管理 API,你可以通过 /projects/{ref}/api-keys 端点 获取项目的 API 凭证。
🌐 Using the management API, you can retrieve a project's API credentials using the /projects/{ref}/api-keys endpoint.
预先填写数据库连接详细信息 #
🌐 Pre-fill database connection details
如果你的集成直接连接到项目的数据库,你可以为用户预填 Postgres 连接详情,其遵循如下模式:
🌐 If your integration directly connects to the project's database, you can pref-fill the Postgres connection details for the user, it follows this schema:
1postgresql://postgres:[DB-PASSWORD]@db.[REF].supabase.co:5432/postgres请注意,你无法通过管理 API 获取数据库密码,所以对于用户已有的项目,你需要在你的界面上收集他们的数据库密码。
🌐 Note that you cannot retrieve the database password via the management API, so for the user's existing projects you will need to collect their database password in your UI.
创建新项目 #
🌐 Create new projects
使用 /v1/projects 接口 来创建一个新项目。
🌐 Use the /v1/projects endpoint to create a new project.
在创建新项目时,你可以让用户提供数据库密码,或者为他们生成一个安全密码。无论哪种情况,都要确保在你这边安全地存储数据库密码,这样你就可以构建 Postgres URI。
🌐 When creating a new project, you can either ask the user to provide a database password, or you can generate a secure password for them. In any case, make sure to securely store the database password on your end which will allow you to construct the Postgres URI.
配置自定义认证 SMTP #
🌐 Configure custom Auth SMTP
你可以使用/config/auth端点配置用户的自定义 SMTP 设置。
🌐 You can configure the user's custom SMTP settings using the /config/auth endpoint.
处理动态重定向网址 #
🌐 Handling dynamic redirect URLs
要在同一个 OAuth 应用中处理多个动态生成的重定向 URL,你可以利用 state 查询参数。在开始 OAuth 流程时,将想要的、经过编码的重定向 URL 包含在 state 参数中。授权完成后,我们会将 state 的值返回给你的应用。然后你可以验证它的完整性,提取正确的重定向 URL,解码并将用户重定向到正确的 URL。
🌐 To handle multiple, dynamically generated redirect URLs within the same OAuth app, you can leverage the state query parameter. When starting the OAuth process, include the desired, encoded redirect URL in the state parameter.
Once authorization is complete, we will sends the state value back to your app. You can then verify its integrity and extract the correct redirect URL, decoding it and redirecting the user to the correct URL.
当前的限制 #
🌐 Current limitations
在我们推出细粒度访问控制之前,只有部分功能可用。如果你需要完整的数据库访问权限,你需要让用户输入他们的数据库密码。
🌐 Only some features are available until we roll out fine-grained access control. If you need full database access, you will need to prompt the user for their database password.