如何为AWS Cognito用户池API计算SecretHash?
在Xamarin.Android中计算AWS Cognito SecretHash(SignUp API必备)
如果你正在用Xamarin.Android开发应用,需要调用AWS Cognito的SignUp API注册用户,那你肯定绕不开计算SecretHash这一步——毕竟当你的用户池客户端配置了密钥时,这个参数是必填项。我把官方的Java示例移植成了适配Xamarin.Android的C#代码,直接就能用,下面给你详细说明:
先搞懂SecretHash是什么
SecretHash是基于用户池客户端密钥、用户名、客户端ID生成的Base64编码HMAC值,具体是用HMAC-SHA256算法,以客户端密钥为加密密钥,把用户名 + 客户端ID作为输入内容计算哈希,再转成Base64编码得到的结果。
我移植好的C#工具类(直接用)
using System; using System.Security.Cryptography; using System.Text; public static class CognitoSecretHashHelper { public static string CalculateSecretHash(string userPoolClientId, string userPoolClientSecret, string username) { if (string.IsNullOrEmpty(userPoolClientId) || string.IsNullOrEmpty(userPoolClientSecret) || string.IsNullOrEmpty(username)) { throw new ArgumentNullException("客户端ID、客户端密钥、用户名这三个参数都不能为空"); } var utf8Encoding = new UTF8Encoding(); var secretKeyBytes = utf8Encoding.GetBytes(userPoolClientSecret); var inputMessage = utf8Encoding.GetBytes(username + userPoolClientId); using (var hmacSha256 = new HMACSHA256(secretKeyBytes)) { var hashResultBytes = hmacSha256.ComputeHash(inputMessage); return Convert.ToBase64String(hashResultBytes); } } }
怎么用这个工具类?
在构造SignUp请求之前,先调用这个方法生成SecretHash,然后把它传入请求参数里就行:
// 替换成你自己的用户池信息和要注册的用户名 string clientId = "你的用户池客户端ID"; string clientSecret = "你的用户池客户端密钥"; string username = "user@example.com"; // 生成SecretHash string secretHash = CognitoSecretHashHelper.CalculateSecretHash(clientId, clientSecret, username); // 接下来就可以用这个secretHash构造SignUpRequest,调用AWS Cognito的SignUp API了
几个要注意的坑
- 只有当你的用户池客户端在AWS控制台开启了「生成客户端密钥」选项时,才需要计算SecretHash;如果没开,直接忽略这个参数就行
- 用户名和客户端ID的拼接顺序绝对不能错,必须是
用户名在前,客户端ID在后,不然计算出来的Hash会无效,API会返回错误 - 客户端密钥属于敏感信息,尽量不要直接硬编码在客户端代码里,如果是安全性要求高的场景,建议通过后端接口来计算并返回SecretHash
内容的提问来源于stack exchange,提问作者mipnw
相关产品推荐
相关产品推荐

