# 开发者 OAuth2 关联授权

### 接入

接入方需要提供 <mark style="background-color:yellow;">应用名称</mark>、<mark style="background-color:yellow;">可信域名</mark>和 <mark style="background-color:yellow;">clientSecret</mark>（如不提供官方将随机生成）

官方会告知你的 <mark style="background-color:yellow;">clientID</mark> 和 <mark style="background-color:yellow;">clientSecret</mark>

### 整体流程

授权登录目前支持 authorization\_code 模式，适用于拥有 server 端的应用授权。

该模式整体流程为：

1\. 第三方发起授权登录请求，显示一个授权登录页面，显示对应的图标和应用名称（如果用户没有登录会跳转登录，成功后返回页面）

<https://afdian.net/oauth2/authorize?response\\_type=code\\&scope=basic\\&client\\_id=><mark style="background-color:red;">yourclientid</mark>\&redirect\_uri=<mark style="background-color:red;">urlencodedhttp</mark>\&state=<mark style="background-color:red;">111</mark>

标红部分替换为你自己的数据。为了方便测试，目前回调地址支持 http、https，线上使用请使用 https 保证数据传输安全。state 用来做安全校验。

2\. 用户点击同意，重定向到 redirect\_uri，会携带 code 和 state。用户拒绝则不会发生重定向

3\. 第三方客户端请求服务器，根据 code 换取 access\_token，此时会返回 user\_id

#### **获取用户ID**

注意：为了安全请务必服务端调用该接口，并且走https协议

secret请仅保存到服务端，如有泄露，请第一时间联系官方进行重置。&#x20;

<https://afdian.net/api/oauth2/access\\_token>

form 表单形式POST提交

| 参数名            | 数值                                   | 备注     |
| -------------- | ------------------------------------ | ------ |
| grant\_type    | authorization\_code                  | 必填，固定值 |
| client\_id     | 分配的client\_id                        | 必填     |
| client\_secret | 分配的密钥                                | 必填     |
| code           | 上个流程返回的 code                         | 必填     |
| redirect\_uri  | 注意仍然填写之前的重定向地址，用来核对数据（这里不需要手动encode） | 必填     |

返回 ec em data 结构，仅当 ec 200时表示成功

```
{
  "ec":200,
  "em":"ok",
  "data":  
      {  
          "user_id": "网站的用户ID",  
          "user_private_id": "同openapi的 user_private_id，如尚未用到，忽略即可"
   }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://guide.afdian.com/creator/oauth2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
