You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R语言连接本地Ghost CMS Admin API遇401错误求助

解决R语言连接Ghost CMS Admin API的401认证错误

问题梳理

尝试用R语言连接本地Ghost CMS的Admin API时遇到401未授权错误,官方文档缺少R语言实现示例,自行编写的代码在创建测试文章时失败。

问题排查与修复方案

代码整体思路正确,但有几处细节需要调整:

  • JWT签名的secret处理错误:Ghost Admin API要求使用原始secret字符串进行HMAC签名,无需用charToRaw()转换,直接传入字符串即可。
  • 确保token生成的准确性:解码生成的token,检查iat(签发时间)、exp(过期时间)、aud(受众)字段是否符合要求,aud需精确为'/admin/'。
  • 请求体格式验证:确认嵌套的JSON结构符合Ghost API要求,字段名保持一致。

修复后的完整代码

api_admin_key <- "xxxxxx:yyyyyyyyyyyyyyy"

api_admin_key <- unlist(strsplit(x = api_admin_key, split = ":"))
names(api_admin_key) <- c("id", "secret")

# 准备JWT头部和载荷
iat <- as.integer(Sys.time())
header <- list(alg = 'HS256', typ = 'JWT', kid = api_admin_key[["id"]])

# 创建JWT令牌(直接使用secret字符串,无需转成Raw)
payload <- jose::jwt_claim(
  iat = iat,
  exp = iat + 5 * 60,
  aud = '/admin/'
)

token <- jose::jwt_encode_hmac(
  claim = payload,
  secret = api_admin_key[["secret"]],
  size = 256,
  header = header
)

# 发送创建文章的请求
url <- 'http://localhost:2368/ghost/api/admin/posts/'
headers <- c(Authorization = paste("Ghost", token))
body <- list(posts = list(
  title = 'Hello World',
  html = "<p>My post content. Work in progress...</p>",
  status = "published"
))

response <- httr::POST(
  url,
  body = body,
  encode = "json",
  httr::add_headers(.headers = headers)
)

# 查看响应内容用于调试
httr::content(response)

额外调试建议

  • 用jose::jwt_decode(token)解码生成的token,验证载荷和头部信息是否符合要求。
  • 确认本地Ghost CMS实例运行正常,API路径无自定义修改。
  • 检查Admin API密钥是否为Ghost后台生成的管理员级别密钥,格式是否正确。

内容的提问来源于stack exchange,提问作者Globoquadrina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:53:18