使用 AWS SDK 的 Amazon Cognito 身分提供者程式碼範例 - AWSSDK 程式碼範例

AWS文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 AWS SDK 的 Amazon Cognito 身分提供者程式碼範例

下列程式碼範例說明如何搭配AWS軟體開發套件 (SDK) 使用 Amazon Cognito 身分供應商。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。

案例是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

其他 資源

開始使用

下列程式碼範例顯示如何開始使用 Amazon Cognito。

C++
適用於 C++ 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

C MakeLists .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) # 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 詳細資訊,請參閱 AWS SDK for C++API 參考ListUserPools中的。

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for Java 2.xAPI 參考ListUserPools中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for JavaScriptAPI 參考ListUserPools中的。