WordPress REST API OAuth2认证实战

本文详解如何为WordPress REST API配置OAuth2认证,让移动APP和第三方应用安全接入。

为什么需要OAuth2

认证方式 安全性 适用场景 问题
用户名密码 同域AJAX 密码泄露风险
Application Passwords 单机应用 无法撤销单个设备
JWT 中高 SPA应用 需要额外插件
OAuth2 第三方APP 标准化、可撤销

安装OAuth2服务器插件

# 安装 WordPress OAuth Server 插件
wp plugin install wordpress-oauth-server --activate

# 或者安装更流行的 JWT Authentication 插件
wp plugin install jwt-authentication-for-wp-rest-api --activate

配置OAuth2服务器

创建OAuth应用

1. WordPress后台  设置  OAuth Server
2. 点击"Add New Client"
3. 填写
   - Client Name: My Mobile App
   - Redirect URI: https://myapp.com/callback
   - Grant Types: Authorization Code + Refresh Token
4. 保存获得 Client ID  Client Secret

插件配置(WP OAuth Server)

// wp-config.php 添加配置
define('OAUTH2_TOKEN_LIFETIME', 86400);      // Access Token 24小时
define('OAUTH2_REFRESH_TOKEN_LIFETIME', 30 * 86400); // Refresh Token 30天
define('OAUTH2_GRANT_TYPES', 'authorization_code,refresh_token');

OAuth2 完整流程

第一步:获取Authorization Code

// 移动APP内打开授权页面
const authUrl = `https://yoursite.com/wp-json/oauth/authorize?
  response_type=code&
  client_id=${CLIENT_ID}&
  redirect_uri=${encodeURIComponent(REDIRECT_URI)}&
  scope=basic`;

// 用WebView加载 authUrl,用户登录并授权

第二步:交换Access Token

// 用户授权后,回调URL包含 code
// https://myapp.com/callback?code=xyz123

const code = getQueryParam('code');

// 用 code 交换 access_token
const response = await fetch('https://yoursite.com/wp-json/oauth/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: new URLSearchParams({
    grant_type:    'authorization_code',
    code:          code,
    redirect_uri:  REDIRECT_URI,
    client_id:     CLIENT_ID,
    client_secret: CLIENT_SECRET,
  }),
});

const { access_token, refresh_token } = await response.json();
// 保存 token(安全存储,如iOS Keychain)

第三步:使用Access Token调用API

// 调用WordPress REST API
const posts = await fetch('https://yoursite.com/wp-json/wp/v2/posts', {
  headers: {
    'Authorization': `Bearer ${access_token}`,
  },
});

// 创建文章(需要对应权限)
const newPost = await fetch('https://yoursite.com/wp-json/wp/v2/posts', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${access_token}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title:   'New Post from App',
    content: 'Posted via OAuth2',
    status:   'publish',
  }),
});

第四步:刷新Token

// Access Token 过期后,用 Refresh Token 获取新的
const response = await fetch('https://yoursite.com/wp-json/oauth/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: new URLSearchParams({
    grant_type:    'refresh_token',
    refresh_token: storedRefreshToken,
    client_id:     CLIENT_ID,
    client_secret: CLIENT_SECRET,
  }),
});

const { access_token: newAccess } = await response.json();

权限范围(Scope)配置

定义Scope

// 在OAuth Server插件中定义Scope
add_filter('json_oauth_scopes', function($scopes) {
    return array(
        'basic'      => '读取公开内容',
        'edit_posts' => '编辑文章',
        'manage'     => '管理设置',
    );
});

请求授权时指定Scope

https://yoursite.com/wp-json/oauth/authorize?
  response_type=code&
  client_id=xxx&
  scope=basic%20edit_posts&    请求多个权限
  redirect_uri=...

安全加固

1. 强制HTTPS

// 禁止HTTP下使用OAuth2
add_action('init', function() {
    if (!is_ssl() && isset($_GET['code'])) {
        wp_die('OAuth2 must use HTTPS');
    }
});

2. 限制Redirect URI

// 在创建OAuth应用时,严格限制Redirect URI
// 只允许预注册的URI,防止授权码劫持

3. 使用PKCE(移动APP必备)

// 生成 code_verifier(随机字符串)
const codeVerifier = generateRandomString(128);

// 计算 code_challenge(SHA256 + Base64URL)
const codeChallenge = base64urlencode(
  await sha256(codeVerifier)
);

// 授权URL中添加
const authUrl = `...&code_challenge=${codeChallenge}&code_challenge_method=S256`;

// 交换Token时提交 code_verifier
const response = await fetch('.../token', {
  body: new URLSearchParams({
    ...
    code_verifier: codeVerifier,
  }),
});

调试工具

使用Postman测试

1. Authorization类型选择 "OAuth 2.0"
2. 配置
   - Grant Type: Authorization Code
   - Callback URL: https://myapp.com/callback
   - Auth URL: https://yoursite.com/wp-json/oauth/authorize
   - Access Token URL: https://yoursite.com/wp-json/oauth/token
   - Client ID: xxx
   - Client Secret: yyy
3. 点击 "Get New Access Token"
4. 授权后自动填充Token

使用curl命令行测试

# 1. 获取Authorization Code(手动在浏览器完成)
# 复制回调URL中的 code

# 2. 交换Access Token
curl -X POST https://yoursite.com/wp-json/oauth/token \
  -d "grant_type=authorization_code" \
  -d "code=xxx" \
  -d "redirect_uri=https://myapp.com/callback" \
  -d "client_id=xxx" \
  -d "client_secret=yyy"

# 3. 使用Access Token
curl https://yoursite.com/wp-json/wp/v2/posts \
  -H "Authorization: Bearer ACCESS_TOKEN"

常见问题

问题 原因 解决方案
403 Forbidden Scope权限不足 检查用户是否有对应能力
Invalid Grant Refresh Token过期 重新授权
Redirect URI mismatch 回调地址不匹配 检查OAuth应用配置
CORS错误 跨域限制 添加Access-Control-Allow-Origin

生产环境检查清单

  • [ ] 强制HTTPS(OAuth2必须)
  • [ ] 使用PKCE(移动APP)
  • [ ] 限制Grant Type(只允许需要的)
  • [ ] Access Token设置短期有效(< 24h)
  • [ ] Refresh Token设置长期有效(可撤销)
  • [ ] 记录Token使用情况(监控异常)
  • [ ] 提供用户撤销授权的界面

通过OAuth2,可以让第三方APP安全接入WordPress,同时保持用户密码不泄露。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。