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

如何在C# WinForm应用中从Amazon Cognito获取用户令牌

在Windows窗体(WinForm)C#应用中从Amazon Cognito获取用户令牌的方法

前置准备

首先安装所需的NuGet包:

  • AWSSDK.CognitoIdentityProvider
  • Amazon.Extensions.CognitoAuthentication

完整实现步骤及代码

  1. 初始化Cognito客户端与用户池
    替换代码中的用户池ID、应用客户端ID为你在AWS控制台中配置的实际值,同时指定正确的AWS区域:

    using Amazon.CognitoIdentityProvider;
    using Amazon.Extensions.CognitoAuthentication;
    using Amazon;
    
    // 配置Cognito参数
    string userPoolId = "你的Cognito用户池ID";
    string clientId = "你的应用客户端ID";
    RegionEndpoint region = RegionEndpoint.USEast1;
    
    // 创建Cognito身份提供者客户端
    var cognitoProvider = new AmazonCognitoIdentityProviderClient(
        new Amazon.Runtime.AnonymousAWSCredentials(), region);
    
    // 初始化用户池
    var userPool = new CognitoUserPool(userPoolId, clientId, cognitoProvider);
    
  2. 创建用户实例并发起认证
    通过用户名和密码发起SRP认证(Cognito推荐的安全认证方式),获取令牌:

    // 从WinForm输入控件获取用户名和密码(示例中直接模拟,实际需替换为用户输入)
    string username = "用户输入的用户名";
    string password = "用户输入的密码";
    
    // 创建Cognito用户实例
    var cognitoUser = new CognitoUser(username, clientId, userPool, cognitoProvider);
    
    try
    {
        // 构建认证请求
        var authRequest = new InitiateSrpAuthRequest
        {
            Password = password
        };
    
        // 异步发起认证
        var authResult = await cognitoUser.StartWithSrpAuthAsync(authRequest);
    
        // 获取令牌
        string accessToken = authResult.AuthenticationResult.AccessToken;
        string idToken = authResult.AuthenticationResult.IdToken;
        string refreshToken = authResult.AuthenticationResult.RefreshToken;
    
        // 后续可将令牌用于API请求或本地存储
        MessageBox.Show($"认证成功!\nAccess Token: {accessToken}\nID Token: {idToken}");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"认证失败:{ex.Message}");
    }
    

关键注意事项

  • 确保你的Cognito应用客户端已启用SRP协议认证(AWS控制台默认开启),且未禁用用户名/密码登录方式。
  • 不要硬编码用户名和密码,应通过WinForm的文本框、密码框等控件收集用户输入。
  • 令牌存在过期时间,可使用RefreshToken调用cognitoUser.StartWithRefreshTokenAuthAsync()方法刷新令牌。
  • 若需管理员级别的认证(如后台系统批量操作),可使用AdminInitiateAuthAsync方法,但需配置对应的IAM权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:25:13