如何用C#程序化获取AWS Cognito授权码?
用C#程序化获取Amazon Cognito授权码(替代托管UI)
你当前使用的StartWithSrpAuthAsync是直接完成用户认证并返回令牌(Token),但你需要的是OAuth2授权码流程中的授权码(Authorization Code)——这是两种完全不同的认证流程。
要实现接收用户名密码并返回授权码的功能,你需要直接模拟OAuth2授权码流程的请求,调用Cognito的/oauth2/authorize端点。以下是具体实现步骤和代码:
前置配置要求
- 确保你的Cognito用户池应用客户端已启用
authorization_code授权类型 - 确认客户端配置的
redirect_uri与代码中使用的一致(比如https://localhost:5001) - 如果客户端设置了密钥(App Client Secret),需要在请求中添加Basic认证头
C#实现代码
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; public async Task<string> GetCognitoAuthorizationCode(string username, string password) { var cognitoDomain = "https://your-user-pool-domain.auth.us-west-2.amazoncognito.com"; var clientId = "your-client-id"; var clientSecret = "your-client-secret"; // 客户端无密钥则忽略 var redirectUri = "https://localhost:5001"; var scope = "openid"; using var httpClient = new HttpClient(new HttpClientHandler { // 关闭自动重定向,手动提取Location头中的code参数 AllowAutoRedirect = false }); // 客户端有密钥时,添加Basic认证头 if (!string.IsNullOrEmpty(clientSecret)) { var authToken = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken); } // 构建请求参数 var formData = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("response_type", "code"), new KeyValuePair<string, string>("client_id", clientId), new KeyValuePair<string, string>("redirect_uri", redirectUri), new KeyValuePair<string, string>("scope", scope), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("grant_type", "password") }); // 发送POST请求到Cognito授权端点 var response = await httpClient.PostAsync($"{cognitoDomain}/oauth2/authorize", formData); // 从重定向响应中提取授权码 if (response.StatusCode == System.Net.HttpStatusCode.Redirect && response.Headers.Location != null) { var queryParams = HttpUtility.ParseQueryString(response.Headers.Location.Query); return queryParams["code"]; } // 处理错误场景 var errorContent = await response.Content.ReadAsStringAsync(); throw new Exception($"获取授权码失败: {errorContent}"); }
关键说明
- 该请求通过POST方式直接传递用户名密码,跳过托管UI跳转步骤
- 关闭自动重定向后,从响应的
Location头中提取Cognito返回的授权码 - 公共客户端(无密钥)无需添加Basic认证头
内容的提问来源于stack exchange,提问作者Dennis
相关产品推荐
相关产品推荐

