Amazon Cognito
开发人员指南
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。请点击 Amazon AWS 入门,可查看中国地区的具体差异

将用户池与适用于 Android 的 移动软件开发工具包结合使用的示例

本主题提供使用适用于 Android 的 移动软件开发工具包执行基本任务的代码示例。由于开发工具包可进行网络调用,所有 API 调用均应从非活动线程发起。

创建 CognitoUserPool

CognitoUserPool userPool = new CognitoUserPool(context, userPoolId, clientId, clientSecret); // user pool can also be created with client app configuration: CognitoUserPool userPool = new CognitoUserPool(context, userPoolId, clientId, clientSecret, clientConfiguration);

注册新用户

// create a handler for registration SignUpHandler handler = new SignUpHandler() { @Override public void onSuccess(CognitoUser user, CognitoUserCodeDeliveryDetails codeDeliveryDetails) { // If the sign up was successful, "user" is a CognitoUser object of the user who was signed up. // "codeDeliveryDetails" will contain details about where the confirmation codes will be delivered. } @Override public void onFailure(Exception exception) { // Sign up failed, code check the exception for cause and perform remedial actions. } }

获取缓存的用户

CognitoUser user = userPool.getCurrentUser();

使用 UserId 创建用户对象

CognitoUser user = userPool.getUser(userId);

确认用户

// create a callback handler for confirm GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // User was successfully confirmed! } @Override public void onFailure(Exception exception) { // Confirmation failed, probe exception for details } } user.confirmSignUp(code, handler);

请求确认代码

// create a callback handler for the confirmation code request GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Confirmation code was successfully sent! } @Override public void onFailure(Exception exception) { // Confirmation code request failed, probe exception for details } } user.resendConfirmationCode(handler);

忘记密码:获取代码以设置新密码

ForgotPasswordHandler handler = new ForgotPasswordHandler() { @Override public void onSuccess() { // Forgot password process completed successfully, new password has been successfully set } @Override public void getResetCode(ForgotPasswordContinuation continuation) { // A code will be sent, use the "continuation" object to continue with the forgot password process // This will indicate where the code was sent String codeSentHere = continuation.getParameters(); // Code to get the code from the user - user dialogs etc. // If the program control has to exit this method, take the "continuation" object. // "continuation" is the only possible way to continue with the process // When the code is available // Set the new password continuation.setPassword(newPassword); // Set the code to verify continuation.setVerificationCode(code); // Let the forgot password process proceed continuation.continueTask(); } /** * This is called for all fatal errors encountered during the password reset process * Probe {@exception} for cause of this failure. * @param exception */ public void onFailure(Exception exception) { // Forgot password processing failed, probe the exception for cause } } user.forgotPassword(handler);

身份验证处理程序:获取令牌

// Implement authentication handler, AuthenticationHandler handler = new AuthenticationHandler() { @Override public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) { // Authentication was successful, the "userSession" will have the current valid tokens // Time to do awesome stuff } @Override public void getAuthenticationDetails(final AuthenticationContinuation continuation, final String userID) { // User authentication details, userId and password are required to continue. // Use the "continuation" object to pass the user authentication details // After the user authentication details are available, wrap them in an AuthenticationDetails class // Along with userId and password, parameters for user pools for Lambda can be passed here // The validation parameters "validationParameters" are passed in as a Map<String, String> AuthenticationDetails authDetails = new AuthenticationDetails(userId, password, validationParameters); // Now allow the authentication to continue continuation.setAuthenticationDetails(authDetails); continuation.continueTask(); } @Override public void getMFACode(final MultiFactorAuthenticationContinuation continuation) { // Multi-factor authentication is required to authenticate // A code was sent to the user, use the code to continue with the authentication // Find where the code was sent to String codeSentHere = continuation.getParameter()[0]; // When the verification code is available, continue to authenticate continuation.setMfaCode(code); continuation.continueTask(); } @Override public void authenticationChallenge(final ChallengeContinuation continuation) { // A custom challenge has to be solved to authenticate // Set the challenge responses // Call continueTask() method to respond to the challenge and continue with authentication. } @Override public void onFailure(final Exception exception) { // Authentication failed, probe exception for the cause } }; user.getSession(handler);

获取用户详细信息

GetDetailsHandler handler = new GetDetailsHandler() { @Override public void onSuccess(final CognitoUserDetails list) { // Successfully retrieved user details } @Override public void onFailure(final Exception exception) { // Failed to retrieve the user details, probe exception for the cause } }; user.getDetails(handler);

获取属性验证代码

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Attribute verification code was successfully sent! } @Override public void onFailure(Exception exception) { // Attribute verification code request failed, probe exception for details } }; user.getAttibuteVerificationCode(attributeName, handler);

验证属性

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Attribute verification was successful! } @Override public void onFailure(Exception exception) { // Attribute verification failed, probe exception for details } }; user.verifyAttribute(attributeName, code, handler);

删除属性

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Attribute deletion was successful! } @Override public void onFailure(Exception exception) { // Attribute deletion failed, probe exception for details } }; user.deleteAttribute(attributeName, handler);

更改密码

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Password change was successful! } @Override public void onFailure(Exception exception) { // Password change failed, probe exception for details } }; user.changePassword(oldPassword, newPassword, handler);

更改或设置用户设置

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Successfully changed settings! } @Override public void onFailure(Exception exception) { // Change failed, probe exception for details } }; // userSettings is an object of the type CognitoUserSettings, CognitoUserSettings userSettings = new CognitoUserSettings(); // Set the user settings userSettings.setSettings(settingName, settingValue); // Now update the new settings to the Amazon Cognito Identity Provider Service user.setUserSettings(userSettings, handler);

删除用户

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Delete was successful! } @Override public void onFailure(Exception exception) { // Delete failed, probe exception for details } }; user.deleteUser(handler);

注销用户

// This has cleared all tokens and this user will have to go through the authentication process to get tokens. user.signOut();

从 CognitoUserSession 获取访问令牌和 ID 令牌

// Session is an object of the type CognitoUserSession String accessToken = session.getAccessToken().getJWT(); String idToken = session.getIdToken().getJWTToken();

列出用户的所有设备

DevicesHandler devicesHandler = new DevicesHandler() { @Override public void onSuccess(List<CognitoDevice> devices) { // devices will contain a list of all remembered devices } @Override public void onFailure(Exception e) { // List devices failed, probe exception for details } }; user.listDevicesInBackground(10, null, devicesHandler);

记住设备

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Successful! } @Override public void onFailure(Exception exception) { // Failed, probe exception for details } }; cognitoDevice.rememberThisDeviceInBackground(handler)

不记住设备

GenericHandler handler = new GenericHandler() { @Override public void onSuccess() { // Successful! } @Override public void onFailure(Exception exception) { // Failed, probe exception for details } }; cognitoDevice.doNotRememberThisDeviceInBackground(handler)

Amazon Pinpoint 分析

以下过程介绍如何在您的 Android Amazon Cognito 应用程序中集成 Amazon Pinpoint。您还需要配置您的 Amazon Cognito 用户池以使用 Amazon Pinpoint。有关与 Amazon Pinpoint 集成的更多信息,请参阅将 Amazon Pinpoint 分析与 Amazon Cognito 用户池结合使用。有关 Amazon Pinpoint 的更多信息,请参阅 Amazon Pinpoint 文档

在创建 CognitoUserPool 实例时包含 Amazon Pinpoint 项目 ID

  1. 登录 AWS 管理控制台并通过以下网址打开 Amazon Pinpoint 控制台:https://console.amazonaws.cn/pinpoint/

  2. 如果您还没有 Amazon Pinpoint 项目,请创建一个。记下 Amazon Pinpoint 项目 ID。

    注意

    还必须为 Amazon Cognito 用户池配置相同的 Amazon Pinpoint 项目 ID。有关更多信息,请参阅 指定用户池分析设置

  3. 在您的 Android Amazon Cognito 应用程序中,当您实例化 Amazon Cognito 用户池实例时,请提供 AWSCognitoIdentityUserPoolConfiguration 并使用上一步中的 Amazon Pinpoint 应用程序 ID 来设置 pinpointAppId

    CognitoUserPool pool = new CognitoUserPool(context, userPoolId, clientId, clientSecret, cognitoRegion, pinpointAppId);

Android 应用程序中的依赖关系

对 Amazon Cognito 身份提供程序 2.6.3 版或更高版本使用 适用于 Android 的 AWS 移动软件开发工具包 以便在您的 Android 应用程序中启用分析。

如果您正在使用 Gradle 构建工具,请在应用程序的 build.gradle 文件中添加以下行。

dependency { compile 'com.amazonaws:aws-android-sdk-cognitoidentityprovider:2.6.3' }

此设置完成后,将可在 Amazon Pinpoint 项目控制台的 Users 选项卡中对用户池使用分析。