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

使用Hyperspace获取Epic EMR的access_token时遇invalid_client错误求助

Epic OAuth2 获取Refresh Token时遇到invalid_client错误排查

我有一套实现用户重定向到启动页面、获取Authorization Code的代码,现在要通过Epic的OAuth2接口获取Access Token和Refresh Token。根据Epic文档,有两种获取access_token的方式:

  • 无Client Secret的方式:代码能正常运行,但这种方式拿不到Refresh Token,所以必须用第二种方式
  • 带Authorization头的方式:按文档要求在请求头传递Authorization信息,但始终返回invalid_client错误,我怀疑问题出在Authorization头的设置上,相关代码如下:
let data = {
    grant_type: "authorization_code",
    code: code,
    redirect_uri: redirectUri,
};

const body = encode(data);
const authHeader = 'Basic ' + base64url.encode(`${clientId}:${encodeURIComponent(clientSecret)}`);

const config = {
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": authHeader,
    },
};

try {
    const response = await axios.post(
        "https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token",
        body,
        config
    );
    return response.data;
} catch (error) {
    console.error(
        "Token Exchange Request Error:",
        error.response ? error.response.data : error.message
    );
    throw error;
}

问题根源及修复方案

invalid_client错误的核心原因是Authorization头的编码方式不符合Basic Auth规范:
Epic要求的Basic Auth是直接将clientId:clientSecret拼接后做Base64编码,不需要对clientSecret做URI编码。代码中对clientSecret调用了encodeURIComponent,会导致凭证解析失败,触发invalid_client错误。

修正后的Authorization头生成代码:

// 移除encodeURIComponent,直接拼接clientId和clientSecret
const authHeader = 'Basic ' + base64url.encode(`${clientId}:${clientSecret}`);

额外验证点

如果修正后仍报错,建议检查以下内容:

  • 确认clientId和clientSecret完全匹配Epic开发者平台上的配置,无拼写错误、多余空格或大小写问题
  • 确认redirect_uri和获取Authorization Code时使用的地址完全一致(包括路径、末尾斜杠、大小写)
  • 确认encode函数正确将表单数据编码为application/x-www-form-urlencoded格式(比如用qs.stringify替代自定义encode函数)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 15:27:33