我需要针对 Amazon Cognito 对用户进行身份验证,并获取 JWT。我的 Amazon Cognito 用户池客户端使用默认的安全远程密码 (SRP) 流程。
我已准备好用户名和密码,现在如何实际使用它们进行 SRP 计算并登录?
我知道有一些库可以为我做到这一点,特别是 AmplifyJS,但我很好奇那些可能更精简、更简单、并且也可以在后端工作的替代方案——例如在集成测试中,我们在 Node.js 或 Bun 中运行。
这个无密码示例解决方案也支持开箱即用的 SRP(和 USERNAME_PASSWORD)流,并且可以在 Node.js 和 Bun 中工作:
import { Passwordless } from "amazon-cognito-passwordless-auth";
import { authenticateWithSRP } from "amazon-cognito-passwordless-auth/srp";
Passwordless.configure({
userPoolId: "<userPoolId>",
clientId: "<clientId>",
clientSecret: "<clientSecret>", // optional
});
authenticateWithSRP({
username: "<username>",
password: "<password>",
}).signedIn.then((tokens) => {
console.log(tokens);
});
请注意,这是由 AWS SA 创建的解决方案,而不是官方 AWS 开发工具包。请在此处查看他们的存储库:https://github.com/aws-samples/amazon-cognito-passwordless-auth
上面的代码示例在后台使用的 SRP 实现主要包含在一个源文件中 – 希望足够容易浏览:https://github.com/aws-samples/amazon-cognito-无密码身份验证/blob/main/client/srp.ts
完全披露:我是编写它的 SA 之一。