使用 Amazon Cognito 身份提供商的代码示例 Amazon SDKs - Amazon Cognito
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Amazon Cognito 身份提供商的代码示例 Amazon SDKs

以下代码示例展示了如何将 Amazon Cognito 身份提供程序与 Amazon 软件开发套件 () SDK 一起使用。

基础知识是向您展示如何在服务中执行基本操作的代码示例。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。

场景是向您展示如何通过在一个服务中调用多个函数或与其他 Amazon Web Services 服务结合来完成特定任务的代码示例。

有关 Amazon SDK开发者指南和代码示例的完整列表,请参阅将此服务与 Amazon SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。

开始使用

以下代码示例展示了如何开始使用 Amazon Cognito。

C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

CMakeLists.txt CMake 文件的代码。

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS cognito-idp) # Set this project's name. project("hello_cognito") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_cognito.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

hello_cognito.cpp 源文件的代码。

#include <aws/core/Aws.h> #include <aws/cognito-idp/CognitoIdentityProviderClient.h> #include <aws/cognito-idp/model/ListUserPoolsRequest.h> #include <iostream> /* * A "Hello Cognito" starter application which initializes an Amazon Cognito client and lists the Amazon Cognito * user pools. * * main function * * Usage: 'hello_cognito' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::CognitoIdentityProvider::CognitoIdentityProviderClient cognitoClient(clientConfig); Aws::String nextToken; // Used for pagination. std::vector<Aws::String> userPools; do { Aws::CognitoIdentityProvider::Model::ListUserPoolsRequest listUserPoolsRequest; if (!nextToken.empty()) { listUserPoolsRequest.SetNextToken(nextToken); } Aws::CognitoIdentityProvider::Model::ListUserPoolsOutcome listUserPoolsOutcome = cognitoClient.ListUserPools(listUserPoolsRequest); if (listUserPoolsOutcome.IsSuccess()) { for (auto &userPool: listUserPoolsOutcome.GetResult().GetUserPools()) { userPools.push_back(userPool.GetName()); } nextToken = listUserPoolsOutcome.GetResult().GetNextToken(); } else { std::cerr << "ListUserPools error: " << listUserPoolsOutcome.GetError().GetMessage() << std::endl; result = 1; break; } } while (!nextToken.empty()); std::cout << userPools.size() << " user pools found." << std::endl; for (auto &userPool: userPools) { std::cout << " user pool: " << userPool << std::endl; } } Aws::ShutdownAPI(options); // Should only be called once. return result; }
  • 有关API详细信息,请参阅 “Amazon SDK for C++ API参考 ListUserPools” 中的。

Go
SDK适用于 Go V2
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service // (Amazon SNS) client and list the topics in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } cognitoClient := cognitoidentityprovider.NewFromConfig(sdkConfig) fmt.Println("Let's list the user pools for your account.") var pools []types.UserPoolDescriptionType paginator := cognitoidentityprovider.NewListUserPoolsPaginator( cognitoClient, &cognitoidentityprovider.ListUserPoolsInput{MaxResults: aws.Int32(10)}) for paginator.HasMorePages() { output, err := paginator.NextPage(context.TODO()) if err != nil { log.Printf("Couldn't get user pools. Here's why: %v\n", err) } else { pools = append(pools, output.UserPools...) } } if len(pools) == 0 { fmt.Println("You don't have any user pools!") } else { for _, pool := range pools { fmt.Printf("\t%v: %v\n", *pool.Name, *pool.Id) } } }
  • 有关API详细信息,请参阅 “Amazon SDK for Go API参考 ListUserPools” 中的。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListUserPools { public static void main(String[] args) { CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() .region(Region.US_EAST_1) .build(); listAllUserPools(cognitoClient); cognitoClient.close(); } public static void listAllUserPools(CognitoIdentityProviderClient cognitoClient) { try { ListUserPoolsRequest request = ListUserPoolsRequest.builder() .maxResults(10) .build(); ListUserPoolsResponse response = cognitoClient.listUserPools(request); response.userPools().forEach(userpool -> { System.out.println("User pool " + userpool.name() + ", User ID " + userpool.id()); }); } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关API详细信息,请参阅 “Amazon SDK for Java 2.x API参考 ListUserPools” 中的。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import { paginateListUserPools, CognitoIdentityProviderClient, } from "@aws-sdk/client-cognito-identity-provider"; const client = new CognitoIdentityProviderClient({}); export const helloCognito = async () => { const paginator = paginateListUserPools({ client }, {}); const userPoolNames = []; for await (const page of paginator) { const names = page.UserPools.map((pool) => pool.Name); userPoolNames.push(...names); } console.log("User pool names: "); console.log(userPoolNames.join("\n")); return userPoolNames; };
  • 有关API详细信息,请参阅 “Amazon SDK for JavaScript API参考 ListUserPools” 中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import boto3 # Create a Cognito Identity Provider client cognitoidp = boto3.client("cognito-idp") # Initialize a paginator for the list_user_pools operation paginator = cognitoidp.get_paginator("list_user_pools") # Create a PageIterator from the paginator page_iterator = paginator.paginate(MaxResults=10) # Initialize variables for pagination user_pools = [] # Handle pagination for page in page_iterator: user_pools.extend(page.get("UserPools", [])) # Print the list of user pools print("User Pools for the account:") if user_pools: for pool in user_pools: print(f"Name: {pool['Name']}, ID: {pool['Id']}") else: print("No user pools found.")
  • 有关API详细信息,请参阅ListUserPools中的 Amazon SDKPython (Boto3) API 参考。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

require 'aws-sdk-cognitoidentityprovider' require 'logger' # CognitoManager is a class responsible for managing AWS Cognito operations # such as listing all user pools in the current AWS account. class CognitoManager def initialize(client) @client = client @logger = Logger.new($stdout) end # Lists and prints all user pools associated with the AWS account. def list_user_pools paginator = @client.list_user_pools(max_results: 10) user_pools = [] paginator.each_page do |page| user_pools.concat(page.user_pools) end if user_pools.empty? @logger.info('No Cognito user pools found.') else user_pools.each do |user_pool| @logger.info("User pool ID: #{user_pool.id}") @logger.info("User pool name: #{user_pool.name}") @logger.info("User pool status: #{user_pool.status}") @logger.info('---') end end end end if $PROGRAM_NAME == __FILE__ cognito_client = Aws::CognitoIdentityProvider::Client.new manager = CognitoManager.new(cognito_client) manager.list_user_pools end
  • 有关API详细信息,请参阅 “Amazon SDK for Ruby API参考 ListUserPools” 中的。