我的应用程序首先使用Cognito LOGIN端点获取授权码。然后,它使用TOKEN端点尝试尝试获取令牌(id_token,access_token,refresh_token),但未授权客户端失败。

我不明白为什么,使用相同的客户端来访问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的状态下调用redirectUri.OriginalUri而不是redirectUri.AbsoluteUri

(我对此没有真正的控制权,因为在我的情况下Xamarin.Auth.OAuthAuthenticator2代表我调用Uri.AbsoluteUri并转换了我给它的redirectUri字符串,因此我将不得不修复Xamarin.Auth)。

09-26 13:37