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

无客户端密钥时,AngularJS应用刷新Cognito Access Token的方法

解决Cognito无客户端密钥时刷新Access Token的invalid_client错误

当Cognito应用客户端未设置客户端密钥(属于公开客户端)时,刷新Access Token需要注意几个关键要点,同时修正你的请求代码即可解决invalid_client错误:

核心问题排查

  • redirect_uri必须完全匹配:你当前用window.location.origin作为redirect_uri,要确保这个值和你在Cognito控制台配置的应用客户端回调URL、以及当初获取refresh_token时使用的redirect_uri完全一致(包括http/https协议、域名、端口,比如https://your-app.com不能写成http://your-app.com)。Cognito对redirect_uri的校验非常严格,细微差异都会触发invalid_client错误。
  • 确认client_id正确性:检查填写的client_id是否和Cognito应用客户端的ID完全一致,避免复制错误或使用了错误的客户端ID。

修正后的请求代码

针对公开客户端场景,请求不需要额外的客户端密钥,但要确保参数编码正确,调整后的jQuery请求代码如下:

let dt = new URLSearchParams();
dt.append('grant_type', 'refresh_token');
dt.append('client_id', 'xxxxxxxxx');
dt.append('redirect_uri', 'https://你的实际回调URL'); // 替换成完全匹配的回调地址
dt.append('refresh_token', 'my_refresh_token');

$.ajax({
    type: 'POST',
    url: "https://example.com/oauth2/token", // 替换成你的Cognito token端点
    data: dt.toString(),
    headers: { 
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function(data) {
        console.log("刷新成功:", data);
        // 此处可更新本地存储的access_token、id_token等凭证
    },
    error: function (jqXHR) {
        console.log("错误详情:", jqXHR.responseText);
    }
});

AngularJS原生$http写法(更贴合项目场景)

如果使用AngularJS的原生$http服务,可采用以下写法:

$http({
    method: 'POST',
    url: 'https://example.com/oauth2/token',
    data: new URLSearchParams({
        grant_type: 'refresh_token',
        client_id: 'xxxxxxxxx',
        redirect_uri: 'https://你的实际回调URL',
        refresh_token: 'my_refresh_token'
    }).toString(),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}).then(function(response) {
    console.log("刷新成功:", response.data);
}, function(error) {
    console.log("错误详情:", error.data);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:50:06