amazon-web-services - AWS Cognito TOKEN 端点无法将授权代码转换为 token

标签 amazon-web-services oauth oauth-2.0 amazon-cognito

我的应用程序首先使用 Cognito LOGIN 端点来获取授权码。然后,它使用 TOKEN 端点尝试获取 token (id_token、access_token、refresh_token),但因 unauthorized_client 而失败。

不明白为什么,用同一个客户端访问LOGIN,成功返回一个授权码。我正在关注 TOKEN endpoint 的文档

string clientId = ...
string clientSecret = ...
Uri redirectUri = new Uri("myapp://myhost");
string authorization_code = ... // obtained via HTTP GET on LOGIN endpoint
string accessTokenUrl = "https://<domain>.auth.<region>.amazoncognito.com/oauth2/token";

var queryValues = new Dictionary<string, string> 
{
    { "grant_type", "authorization_code" },
    { "code",  authorization_code },
    { "redirect_uri", redirectUri.AbsoluteUri },
    { "client_id", clientId},
};

using (HttpClient client = new HttpClient())
{ 
    // Authorization Basic header with Base64Encoded (clientId::clientSecret)
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
        "Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
    string.Format("{0}:{1}",
        clientId, 
        clientSecret))));

    // Url Encoded Content
    var content = new FormUrlEncodedContent(queryValues);

    // HTTPS POST
    HttpResponseMessage response = await client.PostAsync(accessTokenUrl, content).ConfigureAwait(false);

    string text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    // test = {"error" : "unauthorized_client"}
}

最佳答案

问题有两个:

1- System.Uri.AbsoluteUri 在返回的字符串中添加尾随 / 以便我的 redirectUri 变为 myapp://myhost/而不是 myapp://myhost

2- AWS Cognito TOKEN 端点不接受 redirectURI 中的尾随 /

解决方法:

我现在调用 redirectUri.OriginalUri 而不是 redirectUri.AbsoluteUri 我在其中构建查询以保留构建它时的 redirectUri。

(我真的无法控制这个,因为在我的例子中 Xamarin.Auth.OAuthAuthenticator2 代表我调用 Uri.AbsoluteUri 并转换我给的 redirectUri 字符串它,所以我将不得不修复 Xamarin.Auth)。

关于amazon-web-services - AWS Cognito TOKEN 端点无法将授权代码转换为 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861699/

相关文章:

http - WebTestPlugin 和 Http 请求参数(Visual Studio 测试)

java - 如何在 scribe oauthrequest 中添加文件参数?

javascript - 将 Microsoft OAuth 身份验证限制为仅对 Web 应用程序进行身份验证,而不是对所有 Microsoft 服务进行身份验证

amazon-web-services - 如何为未经身份验证的用户使用 AWS Cognito?

amazon-web-services - Cloudfront 的 Cloudformation S3 存储桶主体

amazon-web-services - 使用aws cli为SQS添加发送消息权限

authentication - 如何使 Google 登录 token 的有效期超过 1 小时?

java - spring oauth2sso 是如何工作的?为什么会发生这个重定向序列?

javascript - oauth2 重定向 url 如何用于桌面应用程序?

amazon-web-services - S3 中的 AWS lambda 部署包