我的应用程序首先使用 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/