Gunakan SignUp dengan AWS SDK atau CLI - Amazon Cognito

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan SignUp dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanSignUp.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

/// <summary> /// Sign up a new user. /// </summary> /// <param name="clientId">The client Id of the application.</param> /// <param name="userName">The username to use.</param> /// <param name="password">The user's password.</param> /// <param name="email">The email address of the user.</param> /// <returns>A Boolean value indicating whether the user was confirmed.</returns> public async Task<bool> SignUpAsync(string clientId, string userName, string password, string email) { var userAttrs = new AttributeType { Name = "email", Value = email, }; var userAttrsList = new List<AttributeType>(); userAttrsList.Add(userAttrs); var signUpRequest = new SignUpRequest { UserAttributes = userAttrsList, Username = userName, ClientId = clientId, Password = password }; var response = await _cognitoService.SignUpAsync(signUpRequest); return response.HttpStatusCode == HttpStatusCode.OK; }
  • Untuk detail API, lihat SignUpdi Referensi AWS SDK for .NET API.

C++
SDK untuk C++
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig); Aws::CognitoIdentityProvider::Model::SignUpRequest request; request.AddUserAttributes( Aws::CognitoIdentityProvider::Model::AttributeType().WithName( "email").WithValue(email)); request.SetUsername(userName); request.SetPassword(password); request.SetClientId(clientID); Aws::CognitoIdentityProvider::Model::SignUpOutcome outcome = client.SignUp(request); if (outcome.IsSuccess()) { std::cout << "The signup request for " << userName << " was successful." << std::endl; } else if (outcome.GetError().GetErrorType() == Aws::CognitoIdentityProvider::CognitoIdentityProviderErrors::USERNAME_EXISTS) { std::cout << "The username already exists. Please enter a different username." << std::endl; userExists = true; } else { std::cerr << "Error with CognitoIdentityProvider::SignUpRequest. " << outcome.GetError().GetMessage() << std::endl; return false; }
  • Untuk detail API, lihat SignUpdi Referensi AWS SDK for C++ API.

CLI
AWS CLI

Untuk mendaftar pengguna

Contoh ini mendaftar jane@example.com.

Perintah:

aws cognito-idp sign-up --client-id 3n4b5urk1ft4fl3mg5e62d9ado --username jane@example.com --password PASSWORD --user-attributes Name="email",Value="jane@example.com" Name="name",Value="Jane"

Output:

{ "UserConfirmed": false, "UserSub": "e04d60a6-45dc-441c-a40b-e25a787d4862" }
  • Untuk detail API, lihat SignUpdi Referensi AWS CLI Perintah.

Go
SDK untuk Go V2
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

type CognitoActions struct { CognitoClient *cognitoidentityprovider.Client } // SignUp signs up a user with Amazon Cognito. func (actor CognitoActions) SignUp(clientId string, userName string, password string, userEmail string) (bool, error) { confirmed := false output, err := actor.CognitoClient.SignUp(context.TODO(), &cognitoidentityprovider.SignUpInput{ ClientId: aws.String(clientId), Password: aws.String(password), Username: aws.String(userName), UserAttributes: []types.AttributeType{ {Name: aws.String("email"), Value: aws.String(userEmail)}, }, }) if err != nil { var invalidPassword *types.InvalidPasswordException if errors.As(err, &invalidPassword) { log.Println(*invalidPassword.Message) } else { log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err) } } else { confirmed = output.UserConfirmed } return confirmed, err }
  • Untuk detail API, lihat SignUpdi Referensi AWS SDK for Go API.

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

public static void signUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String email) { AttributeType userAttrs = AttributeType.builder() .name("email") .value(email) .build(); List<AttributeType> userAttrsList = new ArrayList<>(); userAttrsList.add(userAttrs); try { SignUpRequest signUpRequest = SignUpRequest.builder() .userAttributes(userAttrsList) .username(userName) .clientId(clientId) .password(password) .build(); identityProviderClient.signUp(signUpRequest); System.out.println("User has been signed up "); } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Untuk detail API, lihat SignUpdi Referensi AWS SDK for Java 2.x API.

JavaScript
SDK untuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

const signUp = ({ clientId, username, password, email }) => { const client = new CognitoIdentityProviderClient({}); const command = new SignUpCommand({ ClientId: clientId, Username: username, Password: password, UserAttributes: [{ Name: "email", Value: email }], }); return client.send(command); };
  • Untuk detail API, lihat SignUpdi Referensi AWS SDK for JavaScript API.

Kotlin
SDK untuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

suspend fun signUp(clientIdVal: String?, userNameVal: String?, passwordVal: String?, emailVal: String?) { val userAttrs = AttributeType { name = "email" value = emailVal } val userAttrsList = mutableListOf<AttributeType>() userAttrsList.add(userAttrs) val signUpRequest = SignUpRequest { userAttributes = userAttrsList username = userNameVal clientId = clientIdVal password = passwordVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.signUp(signUpRequest) println("User has been signed up") } }
  • Untuk detail API, lihat SignUpdi AWS SDK untuk referensi API Kotlin.

Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

class CognitoIdentityProviderWrapper: """Encapsulates Amazon Cognito actions""" def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None): """ :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client. :param user_pool_id: The ID of an existing Amazon Cognito user pool. :param client_id: The ID of a client application registered with the user pool. :param client_secret: The client secret, if the client has a secret. """ self.cognito_idp_client = cognito_idp_client self.user_pool_id = user_pool_id self.client_id = client_id self.client_secret = client_secret def sign_up_user(self, user_name, password, user_email): """ Signs up a new user with Amazon Cognito. This action prompts Amazon Cognito to send an email to the specified email address. The email contains a code that can be used to confirm the user. When the user already exists, the user status is checked to determine whether the user has been confirmed. :param user_name: The user name that identifies the new user. :param password: The password for the new user. :param user_email: The email address for the new user. :return: True when the user is already confirmed with Amazon Cognito. Otherwise, false. """ try: kwargs = { "ClientId": self.client_id, "Username": user_name, "Password": password, "UserAttributes": [{"Name": "email", "Value": user_email}], } if self.client_secret is not None: kwargs["SecretHash"] = self._secret_hash(user_name) response = self.cognito_idp_client.sign_up(**kwargs) confirmed = response["UserConfirmed"] except ClientError as err: if err.response["Error"]["Code"] == "UsernameExistsException": response = self.cognito_idp_client.admin_get_user( UserPoolId=self.user_pool_id, Username=user_name ) logger.warning( "User %s exists and is %s.", user_name, response["UserStatus"] ) confirmed = response["UserStatus"] == "CONFIRMED" else: logger.error( "Couldn't sign up %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise return confirmed
  • Untuk detail API, lihat SignUpdi AWS SDK for Python (Boto3) Referensi API.

Untuk daftar lengkap panduan pengembang AWS SDK dan contoh kode, lihatMenggunakan layanan ini dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.