我想使用AWS Cognito创建虚拟用户以进行测试。
然后,我使用AWS控制台创建此类用户,但是该用户的状态设置为FORCE_CHANGE_PASSWORD
。使用该值,无法对该用户进行身份验证。
有没有办法更改此状态?
更新从CLI创建用户时的行为相同
我想使用AWS Cognito创建虚拟用户以进行测试。
然后,我使用AWS控制台创建此类用户,但是该用户的状态设置为FORCE_CHANGE_PASSWORD
。使用该值,无法对该用户进行身份验证。
有没有办法更改此状态?
更新从CLI创建用户时的行为相同
Answers:
抱歉,您遇到了困难。我们没有一步一步的过程,您只能创建用户并直接对其进行身份验证。我们将来可能会更改此设置,例如允许管理员设置用户直接可用的密码。目前,当您使用AdminCreateUser
该应用或通过使用该应用注册用户来创建用户时,需要执行额外的步骤,要么迫使用户在登录时更改密码,要么让用户验证电子邮件或电话号码以将用户的状态更改为CONFIRMED
。
--permanent
标志:stackoverflow.com/a/56948249/3165552
我知道已经有一段时间了,但是我认为这可能会对遇到这篇文章的其他人有所帮助。
您可以使用AWS CLI更改用户密码,但这是一个多步骤过程:
步骤1:获取所需用户的会话令牌:
aws cognito-idp admin-initiate-auth --user-pool-id %USER POOL ID% --client-id %APP CLIENT ID% --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=%USERS USERNAME%,PASSWORD=%USERS CURRENT PASSWORD%
如果返回关于的错误
Unable to verify secret hash for client
,请创建另一个没有密码的应用程序客户端,并使用该客户端ID。
第2步:如果第1步成功,它将以Challenge NEW_PASSWORD_REQUIRED
,其他挑战参数和用户会话密钥作为响应。然后,您可以运行第二个命令来发出质询响应:
aws cognito-idp admin-respond-to-auth-challenge --user-pool-id %USER POOL ID% --client-id %CLIENT ID% --challenge-name NEW_PASSWORD_REQUIRED --challenge-responses NEW_PASSWORD=%DESIRED PASSWORD%,USERNAME=%USERS USERNAME% --session %SESSION KEY FROM PREVIOUS COMMAND with ""%
如果您
Invalid attributes given, XXX is missing
在使用格式传递缺少的属性时遇到错误userAttributes.$FIELD_NAME=$VALUE
上面的命令应返回有效的身份验证结果和适当的令牌。
重要提示:为了使此工作正常进行,Cognito用户池必须具有配置了功能的App客户端ADMIN_NO_SRP_AUTH
(此文档中的第5步)。
userAttributes.$FIELD_NAME=$VALUE
(github.com/aws/aws-sdk-js/issues/1290)传递缺失的属性。
--challenge-responses NEW_PASSWORD=password,USERNAME=username,userAttributes.picture=picture,userAttributes.name=name
最终将其添加到AWSCLI:https ://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-set-user-password.html
您可以使用以下方法更改用户密码并更新状态:
aws cognito-idp admin-set-user-password --user-pool-id <your user pool id> --username user1 --password password --permanent
使用此方法之前,您可能需要使用以下方法更新AWS CLI:
pip3 install awscli --upgrade
只需onSuccess: function (result) { ... },
在您的登录功能内添加此代码即可。然后,您的用户将具有CONFIRMED状态。
newPasswordRequired: function(userAttributes, requiredAttributes) {
// User was signed up by an admin and must provide new
// password and required attributes, if any, to complete
// authentication.
// the api doesn't accept this field back
delete userAttributes.email_verified;
// unsure about this field, but I don't send this back
delete userAttributes.phone_number_verified;
// Get these details and call
cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this);
}
this
对新密码的完全挑战)
您可以FORCE_CHANGE_PASSWORD
通过如下调用用户来更改该用户状态respondToAuthChallenge()
:
var params = {
ChallengeName: 'NEW_PASSWORD_REQUIRED',
ClientId: 'your_own3j6...0obh',
ChallengeResponses: {
USERNAME: 'user3',
NEW_PASSWORD: 'changed12345'
},
Session: 'xxxxxxxxxxZDMcRu-5u...sCvrmZb6tHY'
};
cognitoidentityserviceprovider.respondToAuthChallenge(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
之后,您会在控制台中看到
user3
状态为CONFIRMED
。
cognitoidentityserviceprovider.adminInitiateAuth({ AuthFlow: 'ADMIN_NO_SRP_AUTH', ClientId: 'your_own3j63rs8j16bxxxsto25db00obh', UserPoolId: 'us-east-1_DtNSUVT7n', AuthParameters: { USERNAME: 'user3', PASSWORD: 'original_password' } }, callback);
user3
是在控制台中创建的,初始密码为'original_password'
不知道您是否仍在与之抗争,但仅创建了一组测试用户,我awscli
就这样使用了:
aws cognito-idp sign-up \
--region %aws_project_region% \
--client-id %aws_user_pools_web_client_id% \
--username %email_address% \
--password %password% \
--user-attributes Name=email,Value=%email_address%
aws cognito-idp admin-confirm-sign-up \
--user-pool-id %aws_user_pools_web_client_id% \
--username %email_address%
更新:
我现在在NodeJS Lambda中使用此代码(经过翻译放大):
// enable node-fetch polyfill for Node.js
global.fetch = require("node-fetch").default;
global.navigator = {};
const AWS = require("aws-sdk");
const cisp = new AWS.CognitoIdentityServiceProvider();
const Amplify = require("@aws-amplify/core").default;
const Auth = require("@aws-amplify/auth").default;
...
/*
this_user: {
given_name: string,
password: string,
email: string,
cell: string
}
*/
const create_cognito = (this_user) => {
let this_defaults = {
password_temp: Math.random().toString(36).slice(-8),
password: this_user.password,
region: global._env === "prod" ? production_region : development_region,
UserPoolId:
global._env === "prod"
? production_user_pool
: development_user_pool,
ClientId:
global._env === "prod"
? production_client_id
: development_client_id,
given_name: this_user.given_name,
email: this_user.email,
cell: this_user.cell,
};
// configure Amplify
Amplify.configure({
Auth: {
region: this_defaults.region,
userPoolId: this_defaults.UserPoolId,
userPoolWebClientId: this_defaults.ClientId,
},
});
if (!Auth.configure())
return Promise.reject("could not configure amplify");
return new Promise((resolve, reject) => {
let _result = {};
let this_account = undefined;
let this_account_details = undefined;
// create cognito account
cisp
.adminCreateUser({
UserPoolId: this_defaults.UserPoolId,
Username: this_defaults.given_name,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
MessageAction: "SUPPRESS",
TemporaryPassword: this_defaults.password_temp,
UserAttributes: [
{ Name: "given_name", Value: this_defaults.given_name },
{ Name: "email", Value: this_defaults.email },
{ Name: "phone_number", Value: this_defaults.cell },
{ Name: "email_verified", Value: "true" },
],
})
.promise()
.then((user) => {
console.warn(".. create_cognito: create..");
_result.username = user.User.Username;
_result.temporaryPassword = this_defaults.password_temp;
_result.password = this_defaults.password;
// sign into cognito account
return Auth.signIn(_result.username, _result.temporaryPassword);
})
.then((user) => {
console.warn(".. create_cognito: signin..");
// complete challenge
return Auth.completeNewPassword(user, _result.password, {
email: this_defaults.email,
phone_number: this_defaults.cell,
});
})
.then((user) => {
console.warn(".. create_cognito: confirmed..");
this_account = user;
// get details
return Auth.currentAuthenticatedUser();
})
.then((this_details) => {
if (!(this_details && this_details.attributes))
throw "account creation failes";
this_account_details = Object.assign({}, this_details.attributes);
// signout
return this_account.signOut();
})
.then(() => {
console.warn(".. create_cognito: complete");
resolve(this_account_details);
})
.catch((err) => {
console.error(".. create_cognito: error");
console.error(err);
reject(err);
});
});
};
我正在设置一个临时密码,然后将其重置为用户请求的密码。
旧帖子:
您可以使用amazon-cognito-identity-js SDK解决此问题,方法是:在创建帐户后,使用临时密码进行身份验证cognitoidentityserviceprovider.adminCreateUser()
,然后cognitoUser.completeNewPasswordChallenge()
在cognitoUser.authenticateUser( ,{newPasswordRequired})
创建用户的函数内部运行-。
我在AWS lambda中使用以下代码来创建启用的Cognito用户帐户。我相信它可以优化,请耐心等待。这是我的第一篇文章,对JavaScript还是很陌生。
var AWS = require("aws-sdk");
var AWSCognito = require("amazon-cognito-identity-js");
var params = {
UserPoolId: your_poolId,
Username: your_username,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
MessageAction: "SUPPRESS",
TemporaryPassword: your_temporaryPassword,
UserAttributes: [
{ Name: "given_name", Value: your_given_name },
{ Name: "email", Value: your_email },
{ Name: "phone_number", Value: your_phone_number },
{ Name: "email_verified", Value: "true" }
]
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
let promise = new Promise((resolve, reject) => {
cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
promise
.then(data => {
// login as new user and completeNewPasswordChallenge
var anotherPromise = new Promise((resolve, reject) => {
var authenticationDetails = new AWSCognito.AuthenticationDetails({
Username: your_username,
Password: your_temporaryPassword
});
var poolData = {
UserPoolId: your_poolId,
ClientId: your_clientId
};
var userPool = new AWSCognito.CognitoUserPool(poolData);
var userData = {
Username: your_username,
Pool: userPool
};
var cognitoUser = new AWSCognito.CognitoUser(userData);
let finalPromise = new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(authResult) {
cognitoUser.getSession(function(err) {
if (err) {
} else {
cognitoUser.getUserAttributes(function(
err,
attResult
) {
if (err) {
} else {
resolve(authResult);
}
});
}
});
},
onFailure: function(err) {
reject(err);
},
newPasswordRequired(userAttributes, []) {
delete userAttributes.email_verified;
cognitoUser.completeNewPasswordChallenge(
your_newPoassword,
userAttributes,
this
);
}
});
});
finalPromise
.then(finalResult => {
// signout
cognitoUser.signOut();
// further action, e.g. email to new user
resolve(finalResult);
})
.catch(err => {
reject(err);
});
});
return anotherPromise;
})
.then(() => {
resolve(finalResult);
})
.catch(err => {
reject({ statusCode: 406, error: err });
});
对于Java SDK,假设您已设置Cognito客户端,并且您的用户处于FORCE_CHANGE_PASSWORD状态,则可以执行以下操作以使用户CONFIRMED ...然后正常进行身份验证。
AdminCreateUserResult createUserResult = COGNITO_CLIENT.adminCreateUser(createUserRequest());
AdminInitiateAuthResult authResult = COGNITO_CLIENT.adminInitiateAuth(authUserRequest());
Map<String,String> challengeResponses = new HashMap<>();
challengeResponses.put("USERNAME", USERNAME);
challengeResponses.put("NEW_PASSWORD", PASSWORD);
RespondToAuthChallengeRequest respondToAuthChallengeRequest = new RespondToAuthChallengeRequest()
.withChallengeName("NEW_PASSWORD_REQUIRED")
.withClientId(CLIENT_ID)
.withChallengeResponses(challengeResponses)
.withSession(authResult.getSession());
COGNITO_CLIENT.respondToAuthChallenge(respondToAuthChallengeRequest);
希望它对那些集成测试有所帮助(对格式感到抱歉)
基本上,这是相同的答案,但对于.Net C#SDK:
以下将使用所需的用户名和密码进行完整的管理员用户创建。具有以下用户模型:
public class User
{
public string Username { get; set; }
public string Password { get; set; }
}
您可以使用以下方法创建用户并使其可供使用:
public void AddUser(User user)
{
var tempPassword = "ANY";
var request = new AdminCreateUserRequest()
{
Username = user.Username,
UserPoolId = "MyuserPoolId",
TemporaryPassword = tempPassword
};
var result = _cognitoClient.AdminCreateUserAsync(request).Result;
var authResponse = _cognitoClient.AdminInitiateAuthAsync(new AdminInitiateAuthRequest()
{
UserPoolId = "MyuserPoolId",
ClientId = "MyClientId",
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
AuthParameters = new Dictionary<string, string>()
{
{"USERNAME",user.Username },
{"PASSWORD", tempPassword}
}
}).Result;
_cognitoClient.RespondToAuthChallengeAsync(new RespondToAuthChallengeRequest()
{
ClientId = "MyClientId",
ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED,
ChallengeResponses = new Dictionary<string, string>()
{
{"USERNAME",user.Username },
{"NEW_PASSWORD",user.Password }
},
Session = authResponse.Session
});
}
如果您尝试从控制台以管理员身份更改状态。创建用户后,请按照以下步骤操作。
我知道这是相同的答案,但认为这可能对Go
开发人员社区有所帮助。基本上是发起身份验证请求,获取会话并响应挑战NEW_PASSWORD_REQUIRED
func sessionWithDefaultRegion(region string) *session.Session {
sess := Session.Copy()
if v := aws.StringValue(sess.Config.Region); len(v) == 0 {
sess.Config.Region = aws.String(region)
}
return sess
}
func (c *CognitoAppClient) ChangePassword(userName, currentPassword, newPassword string) error {
sess := sessionWithDefaultRegion(c.Region)
svc := cognitoidentityprovider.New(sess)
auth, err := svc.AdminInitiateAuth(&cognitoidentityprovider.AdminInitiateAuthInput{
UserPoolId:aws.String(c.UserPoolID),
ClientId:aws.String(c.ClientID),
AuthFlow:aws.String("ADMIN_NO_SRP_AUTH"),
AuthParameters: map[string]*string{
"USERNAME": aws.String(userName),
"PASSWORD": aws.String(currentPassword),
},
})
if err != nil {
return err
}
request := &cognitoidentityprovider.AdminRespondToAuthChallengeInput{
ChallengeName: aws.String("NEW_PASSWORD_REQUIRED"),
ClientId:aws.String(c.ClientID),
UserPoolId: aws.String(c.UserPoolID),
ChallengeResponses:map[string]*string{
"USERNAME":aws.String(userName),
"NEW_PASSWORD": aws.String(newPassword),
},
Session:auth.Session,
}
_, err = svc.AdminRespondToAuthChallenge(request)
return err
}
这是一个单元测试:
import (
"fmt"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestCognitoAppClient_ChangePassword(t *testing.T) {
Convey("Testing ChangePassword!", t, func() {
err := client.ChangePassword("user_name_here", "current_pass", "new_pass")
Convey("Testing ChangePassword Results!", func() {
So(err, ShouldBeNil)
})
})
}
好。我终于有了代码,管理员可以在其中创建新用户。过程如下:
步骤1是困难的部分。这是我在Node JS中创建用户的代码:
let params = {
UserPoolId: "@cognito_pool_id@",
Username: username,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
UserAttributes: [
{ Name: "given_name", Value: firstName },
{ Name: "family_name", Value: lastName},
{ Name: "name", Value: firstName + " " + lastName},
{ Name: "email", Value: email},
{ Name: "custom:title", Value: title},
{ Name: "custom:company", Value: company + ""}
],
};
let cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();
cognitoIdentityServiceProvider.adminCreateUser(params, function(error, data) {
if (error) {
console.log("Error adding user to cognito: " + error, error.stack);
reject(error);
} else {
// Uncomment for interesting but verbose logging...
//console.log("Received back from cognito: " + CommonUtils.stringify(data));
cognitoIdentityServiceProvider.adminUpdateUserAttributes({
UserAttributes: [{
Name: "email_verified",
Value: "true"
}],
UserPoolId: "@cognito_pool_id@",
Username: username
}, function(err) {
if (err) {
console.log(err, err.stack);
} else {
console.log("Success!");
resolve(data);
}
});
}
});
基本上,您需要发送第二条命令以强制将电子邮件视为已验证。用户仍然需要转到其电子邮件以获取临时密码(该密码也将验证电子邮件)。但是如果没有第二次呼叫将电子邮件设置为经过验证,您将无法获得正确的呼叫以重置其密码。