使用Python调用WordPress API自动发文章遇权限问题求助
WordPress REST API 401权限错误排查方案
问题描述
使用Python脚本通过Basic Auth调用WordPress REST API创建文章时,返回以下错误:
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}
已确认用户test拥有管理员权限,但问题未解决。
排查与解决步骤
1. 验证应用密码与Base64编码正确性
- 确认使用的密码是WordPress用户个人设置中生成的应用密码,复制时需完整保留空格,不能遗漏字符。
- 手动验证Base64编码结果:在终端执行以下命令,对比脚本生成的token是否一致:
若结果与脚本输出不同,说明编码过程存在错误,需检查字符串拼接是否正确。echo -n 'test:P8zJ xns7 OU1g p8iS jaVt fffU' | base64
2. 启用REST API的Basic Auth支持
- WordPress 5.6及以上版本默认支持应用密码+Basic Auth,但部分环境(如多站点、主机限制)可能需要额外配置:
- 若为旧版本WordPress,需安装
Application Passwords插件。 - 检查安全插件(如Wordfence、iThemes Security)是否拦截了Basic Auth请求,需在插件设置中添加允许规则,放行REST API端点的Basic Auth验证。
- 若为旧版本WordPress,需安装
3. 确认API端点有效性
- 将
api_url中的<website.com>替换为实际域名,例如https://yourdomain.com/wp-json/wp/v2/posts。 - 用浏览器或curl发送GET请求访问该端点,确认REST API可正常响应:
若无法访问,需先排查REST API的可用性问题。curl https://yourdomain.com/wp-json/wp/v2/posts
4. 检查用户实际权限范围
- 尽管用户标记为管理员,仍需确认:
- 在多站点环境中,该管理员是否拥有目标站点的权限,而非仅子站点权限。
- 用户是否实际拥有
publish_posts权限:进入WordPress后台→用户→编辑用户,查看权限列表是否包含「发布文章」。
5. 验证请求格式正确性
- 确保请求头
Authorization格式正确:Basic后紧跟Base64编码字符串,注意Basic与字符串之间有一个空格。 - 可尝试显式设置
Content-Type头(虽然requests.post的json参数已自动处理),修改请求代码:wordpress_header = { 'Authorization': f'Basic {token}', 'Content-Type': 'application/json' } response = requests.post(api_url, headers=wordpress_header, json=data)
修改后的示例脚本
import requests import base64 wordpress_user = "test" wordpress_password = "P8zJ xns7 OU1g p8iS jaVt fffU" # 验证编码正确性 credentials = f"{wordpress_user}:{wordpress_password}" token = base64.b64encode(credentials.encode()).decode('utf-8') print(f"Generated token: {token}") wordpress_header = {'Authorization': f'Basic {token}'} def create_wordpress_post(): api_url = 'https://your-actual-domain.com/wp-json/wp/v2/posts' data = { 'title': 'Example wordpress post', 'status': 'publish', 'slug': 'example-post', 'content': 'This is the content of the post' } response = requests.post(api_url, headers=wordpress_header, json=data) print(f"Status Code: {response.status_code}") print(response.text) create_wordpress_post()
内容的提问来源于stack exchange,提问作者ippsec
相关产品推荐
相关产品推荐

