首页 > 解决方案 > 带有 OpenID 的 AWS Cognito 使用 .NET Core 失败时会出现*错误兑换代码:invalid_client*

问题描述

环境

背景

我们在用户机器上运行了多个 Windows 应用程序(WPF 和 WinForms)。用户在 AWS Cognito 的自定义用户池中进行管理。与其他服务的联合存在,但超出了这项工作的范围。SSO 应用程序会显示一个登录屏幕,用户可以在其中输入他们的凭据并通过 Cognito 进行身份验证,然后返回一个身份验证代码。登录机制是通过 OpenID Connect。

问题陈述

用户通过 Cognito 成功通过身份验证,但 OIDC 登录调用给出如下错误消息:-

Error redeeming code: invalid_client / no description

从 Cognito 收到的响应如下,结果代码为成功:-

http://localhost/myBusinessApp?code=5a0507ed-5230-408d-&state=KHfMkdZphxxxxxxxxxx

**代码 **

认证应用

            var options = new OidcClientOptions()
        {
            Authority = _authenticationConfig.Value.Authority,
            ClientId = _authenticationConfig.Value.ClientId,
            ClientSecret = _authenticationConfig.Value.ClientSecret,  
            Scope = _authenticationConfig.Value.Scope,
            RedirectUri = _authenticationConfig.Value.RedirectUri,
            Browser = new CEFBrowser(),
            Policy = new Policy()
            {
                Discovery = new DiscoveryPolicy()
                {
                    ValidateIssuerName = false ,  /* added for Cognito only */
                    ValidateEndpoints = false /* added for Cognito only */    
                }
            }, 
            Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode  /* default, but just for clarity */
        };               
        
        _oidcClient = new IdentityModel.OidcClient.OidcClient(options);

        LoginResult result;
        try
        {
            result = await _oidcClient.LoginAsync();
        }
        catch (Exception ex)
        {
            Message.Text = $"Unexpected Error: {ex.Message}";
            return;
        }

        if (result.IsError)
               // Log error (always happen)

浏览器调用 Cognito

这总是成功重定向到配置的 RedirectUrl

       webBrowser.LoadingStateChanged += (s, e) =>
       {
           var url = e.Browser.MainFrame.Url;
           if (url.StartsWith(_options.EndUrl))
           {
               result = new BrowserResult()
               {
                   ResultType = BrowserResultType.Success,
                   Response = url
               };

               signal.Release();

               webBrowser.Dispatcher.Invoke(() => window.Close());
           }
       };

认知配置

已经探索的教程

提琴手响应

提琴手响应序列

标签: c#amazon-web-services.net-coreamazon-cognitoopenid-connect

解决方案


最后在添加单元测试支持后,我意识到由于数据结构不正确,ClientSecret 没有通过。添加后,该应用程序正常运行。


推荐阅读