

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 [AWS SDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# `AdminSetUserPassword` 搭配 AWS SDK 或 CLI 使用
<a name="cognito-identity-provider_example_cognito-identity-provider_AdminSetUserPassword_section"></a>

下列程式碼範例示範如何使用 `AdminSetUserPassword`。

動作範例是大型程式的程式碼摘錄，必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作：
+  [進行 Amazon Cognito 使用者身分驗證後，可使用 Lambda 函數撰寫自訂活動資料](cognito-identity-provider_example_cross_CognitoCustomActivityLog_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**將使用者密碼設定為管理員**  
下列 `admin-set-user-password` 範例會永久設定 diego@example.com 的密碼。  

```
aws cognito-idp admin-set-user-password \
    --user-pool-id us-west-2_EXAMPLE \
    --username diego@example.com \
    --password MyExamplePassword1! \
    --permanent
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon Cognito 開發人員指南*》中的[密碼、密碼還原和密碼政策](https://docs.aws.amazon.com/cognito/latest/developerguide/managing-users-passwords.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [AdminSetUserPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-set-user-password.html)。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)中設定和執行。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
+  如需 API 詳細資訊，請參閱《適用於 Go 的 AWS SDK API 參考》**中的 [AdminSetUserPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.AdminSetUserPassword)。

------