You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.5 KiB
Markdown

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
title: 配置 Clerk 身份验证服务 - 完整指南
description: 学习如何配置 Clerk 身份验证服务,获取公私钥和设置 Webhook。
tags:
- Clerk
- 身份验证
- Webhook
- 环境变量
---
# 配置 Clerk 身份验证服务
前往 [Clerk](https://clerk.com?utm_source=lobehub&utm_medium=docs) 注册并创建应用,获取相应的 Public Key 和 Secret Key。
## 获取环境变量
<Steps>
### 添加公、私钥环境变量
添加 `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY``CLERK_SECRET_KEY` 环境变量。你可以在菜单中点击「API Keys」然后复制对应的值获取该环境变量。
<Image
alt={'在 Clerk 中找到对应的公私钥环境变量'}
src={'https://github.com/lobehub/lobe-chat/assets/28616219/89883703-7a1a-4a11-b944-5d804544e57c'}
></Image>
此步骤所需的环境变量如下:
```shell
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_xxxxxxxxxxx
CLERK_SECRET_KEY=sk_live_xxxxxxxxxxxxxxxxxxxxxx
```
### 在 Clerk 中创建并配置 Webhook
由于我们让 Clerk 完全接管用户鉴权与管理,因此我们需要在 Clerk 用户生命周期变更时(创建、更新、删除)中通知我们的应用并存储落库。我们通过 Clerk 提供的 Webhook 来实现这一诉求。
我们需要在 Clerk 的 Webhooks 中添加一个端点Endpoint告诉 Clerk 当用户发生变更时,向这个端点发送通知。
<Image
alt={'Clerk 添加 Webhooks 端点'}
src={'https://github.com/lobehub/lobe-chat/assets/28616219/f50f47fb-5e8e-4930-bf4e-8cf6f5b8afb9'}
></Image>
在 endppint 中填写你的项目 URL`https://your-project.com/api/webhooks/clerk`。然后在订阅事件Subscribe to events勾选 user 的三个事件(`user.created` 、`user.deleted`、`user.updated`),然后点击创建。
<Callout type={'warning'}>URL的`https://`不可缺失须保持URL的完整性</Callout>
<Image
alt={'添加 Clerk Webhooks 时,配置 URL 和用户事件'}
src={'https://github.com/lobehub/lobe-chat/assets/28616219/0249ea56-ab17-4aa9-a56c-9ebd556c2645'}
></Image>
### 将 Webhook 秘钥添加到环境变量
创建完毕后,可以在右下角找到该 Webhook 的秘钥:
<Image
alt={'查看 Clerk Webhooks 秘钥'}
src={'https://github.com/lobehub/lobe-chat/assets/28616219/fab4abb2-584b-49de-9340-813382951635'}
></Image>
这个秘钥所对应的环境变量名为 `CLERK_WEBHOOK_SECRET`
```shell
CLERK_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxxxx
```
</Steps>
这样,你已经成功配置了 Clerk 身份验证服务。