如何使用Amplify限制单用户同时登录的设备数量最多为3台?
Amplify 限制单用户最大3台设备同时登录实现方案
Amplify的身份验证能力底层基于AWS Cognito实现,你可以通过Cognito设备跟踪+自定义触发器的组合实现该需求,具体步骤如下:
步骤1:开启Cognito用户池设备跟踪
- 你可以通过Amplify CLI直接修改配置,执行
amplify update auth,按交互提示找到「设备跟踪」相关配置,选择始终记住用户设备,完成后执行amplify push将配置同步到云端 - 也可以直接登录AWS控制台,找到Amplify项目对应的Cognito用户池,在「设备跟踪」配置页手动开启即可
步骤2:绑定预身份验证Lambda触发器
该触发器会在每次用户发起登录请求时触发,用来校验当前用户已登录的设备数量是否超过上限:
- 新建一个Node.js运行环境的Lambda函数,参考代码如下:
const { CognitoIdentityProviderClient, ListDevicesCommand, AdminForgetDeviceCommand } = require("@aws-sdk/client-cognito-identity-provider"); const cognitoClient = new CognitoIdentityProviderClient({ region: process.env.COGNITO_REGION }); const MAX_ALLOWED_DEVICES = 3; exports.handler = async (event) => { const { userPoolId, userName: username } = event; try { // 获取当前用户的活跃设备列表,仅统计30天内有登录记录的设备 const deviceList = await cognitoClient.send(new ListDevicesCommand({ UserPoolId: userPoolId, Username: username, Limit: MAX_ALLOWED_DEVICES + 1 })); const validDevices = (deviceList.Devices || []).filter(device => device.DeviceLastModifiedDate > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) ); if (validDevices.length >= MAX_ALLOWED_DEVICES) { // 可选逻辑:如果需要踢掉最早登录的设备,取消注释下方代码即可 // const earliestDevice = validDevices.sort((a,b) => a.DeviceLastModifiedDate - b.DeviceLastModifiedDate)[0]; // await cognitoClient.send(new AdminForgetDeviceCommand({ // UserPoolId: userPoolId, // Username: username, // DeviceKey: earliestDevice.DeviceKey // })); // return event; // 默认逻辑:直接阻止新登录,返回错误提示 throw new Error("已达到最大同时登录设备上限(3台),请先在其他设备退出登录后重试"); } return event; } catch (err) { throw new Error(err.message); } };
- 为Lambda函数配置IAM权限,允许其调用
cognito-idp:ListDevices、cognito-idp:AdminForgetDevice接口 - 进入Cognito用户池的「触发器」配置页,将上述Lambda函数绑定到预身份验证触发源,保存配置
步骤3:React前端适配
你需要在前端的登录、登出逻辑中补充设备相关的调用:
- 登录成功后标记当前设备为可信任设备:
import { Auth } from 'aws-amplify'; const login = async (username, password) => { try { const user = await Auth.signIn(username, password); // 记住当前设备 await Auth.rememberDevice(); // 后续登录成功业务逻辑 } catch (err) { // 捕获设备超限错误,提示给用户 if (err.message.includes("最大同时登录设备上限")) { alert(err.message); } // 其他错误处理逻辑 } };
- 登出时主动清除当前设备记录,释放配额:
const logout = async () => { try { await Auth.forgetDevice(); await Auth.signOut(); } catch (err) { console.error("登出失败", err); } };
内容的提问来源于stack exchange,提问作者Akhil Chandran
相关产品推荐
相关产品推荐

