Slack
获取你的 Slack 凭证
要使用 Slack 作为社交提供者,你需要创建一个 Slack 应用并获取你的凭证。
- 访问 Your Apps on Slack API 并点击“创建新应用”
- 选择“从头开始”,为你的应用命名并选择开发工作区
- 在你的应用设置中,导航到“OAuth 与权限”
- 在“重定向 URL”下,添加你的重定向 URL:
- 用于本地开发:
http://localhost:3000/api/auth/callback/slack - 用于生产环境:
https://yourdomain.com/api/auth/callback/slack
- 用于本地开发:
- 从“基本信息”页面复制你的客户端 ID 和客户端密钥
Slack 在生产环境中要求重定向 URL 使用 HTTPS。对于本地开发,你可以使用像 ngrok 这样的工具来创建一个安全隧道。
配置提供者
要配置提供者,你需要在身份验证配置中将 clientId 和 clientSecret 传递给 socialProviders.slack。
import { betterAuth } from "better-auth"
export const auth = betterAuth({
socialProviders: {
slack: {
clientId: process.env.SLACK_CLIENT_ID as string,
clientSecret: process.env.SLACK_CLIENT_SECRET as string,
},
},
})用法
【Usage】
使用 Slack 登录
【Sign In with Slack】
要使用 Slack 登录,你可以使用客户端提供的 signIn.social 函数。signIn 函数接收一个具有以下属性的对象:
【To sign in with Slack, you can use the signIn.social function provided by the client. The signIn function takes an object with the following properties:】
provider:要使用的提供者。它应设置为slack。
import { createAuthClient } from "better-auth/client";
const authClient = createAuthClient();
const signIn = async () => {
const data = await authClient.signIn.social({ provider: "slack" });
};请求附加权限
【Requesting Additional Scopes】
默认情况下,Slack 使用 OpenID Connect 范围:openid、profile 和 email。你可以在登录时请求额外的 Slack 范围:
【By default, Slack uses OpenID Connect scopes: openid, profile, and email. You can request additional Slack scopes during sign-in:】
const signInWithSlack = async () => {
await authClient.signIn.social({
provider: "slack",
scopes: ["channels:read", "chat:write"], // Additional Slack API scopes
});
};工作区专用登录
【Workspace-Specific Sign In】
如果你想限制登录到特定的 Slack 工作区,可以传递 team 参数:
【If you want to restrict sign-in to a specific Slack workspace, you can pass the team parameter:】
socialProviders: {
slack: {
clientId: process.env.SLACK_CLIENT_ID as string,
clientSecret: process.env.SLACK_CLIENT_SECRET as string,
team: "T1234567890", // Your Slack workspace ID
},
}登录后使用 Slack API
【Using Slack API After Sign In】
身份验证成功后,你可以通过会话访问用户的 Slack 信息。访问令牌可用于向 Slack API 发起请求:
【After successful authentication, you can access the user's Slack information through the session. The access token can be used to make requests to the Slack API:】
const session = await authClient.getSession();
if (session?.user) {
// Access Slack-specific data
const slackUserId = session.user.id; // This is the Slack user ID
// The access token is stored securely on the server
}Slack 提供商默认使用 OpenID Connect,它提供基本的用户信息。如果你需要访问其他 Slack API,请确保在登录时请求相应的权限范围。