gpt4 book ai didi

android - 如何在 android 中设置 Cognito 身份池?

转载 作者:行者123 更新时间:2023-11-30 00:50:04 27 4
gpt4 key购买 nike

我对 aws cognito 完全陌生,这些指南到处都是,我有点迷路了。在我的 aws 帐户中,我创建了一个身份池,现在我想尝试从我的 android 应用程序创建一个新用户,但它无法创建用户或无法连接到认知池。我不确定我是否在写这篇文章,希望得到您的指导!

这是我目前所拥有的。

public class aws extends AppCompatActivity
{
private EditText firstName,lastName,email,password;
private Button loginButton;
private String poolId,clientId,clientSecret;
CognitoUserPool userPool;
CognitoUserAttributes userAttributes;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);

CognitoCachingCredentialsProvider credentialsProvider = new
CognitoCachingCredentialsProvider(
getApplicationContext(), // Context
"IDENTITY POOL_ID", // Identity Pool ID
MY_REGION // Region
);
CognitoSyncManager syncClient = new CognitoSyncManager(
getApplicationContext(), // Context
MY_REGION, // Region
credentialsProvider
);
Dataset dataset = syncClient.openOrCreateDataset("myDataset");
dataset.put("myKey", "myValue");
dataset.synchronize(new DefaultSyncCallback() {
@Override
public void onSuccess(Dataset dataset, List newRecords) {
//Your handler code here
}
});

poolId = "MY_POOL_ID";
clientId = "MY_CLIENT_ID";
clientSecret = "MY_CLIENT_SECRET";
ClientConfiguration clientConfiguration = new ClientConfiguration();
// Create a CognitoUserPool object to refer to your user pool
userPool = new CognitoUserPool(getBaseContext(), poolId, clientId, clientSecret, clientConfiguration);

bindActivity();
}
private void bindActivity()
{
firstName = (EditText) findViewById(R.id.register_firstNameET);
lastName = (EditText) findViewById(R.id.register_lastNameET);
email = (EditText) findViewById(R.id.register_emailET);
password = (EditText) findViewById(R.id.register_passwordET);
loginButton = (Button) findViewById(R.id.intro_register_zivit_button);
loginButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
setUpCognito();
}
});
}
private void setUpCognito()
{
// Create a CognitoUserAttributes object and add user attributes
userAttributes = new CognitoUserAttributes();
// Add the user attributes. Attributes are added as key-value pairs

// Adding user's given name.
// Note that the key is "given_name" which is the OIDC claim for given name
userAttributes.addAttribute("given_name", firstName.getText().toString());

// Adding user's lastName
userAttributes.addAttribute("family_Name", lastName.getText().toString());
// Adding user's email address
userAttributes.addAttribute("email", email.getText().toString());

setUpCognitoHandler();

}

private void setUpCognitoHandler()
{
SignUpHandler signupCallback = new SignUpHandler() {

@Override
public void onSuccess(CognitoUser cognitoUser, boolean userConfirmed, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails)
{
Log.d("myCognito","sign up succeeded!");
// Sign-up was successful

// Check if this user (cognitoUser) needs to be confirmed
if(!userConfirmed)
{
Log.d("myCognito","not confirmed! Need to confirm");
confirmUser();
// This user must be confirmed and a confirmation code was sent to the user
// cognitoUserCodeDeliveryDetails will indicate where the confirmation code was sent
// Get the confirmation code from user
}
else {
Log.d("myCognito","confirmed!");
// The user has already been confirmed
}
}

@Override
public void onFailure(Exception exception)
{
Log.d("myCognito","sign up failed!");
// Sign-up failed, check exception for the cause
}
};
userPool.signUpInBackground("user1ID", password.getText().toString(), userAttributes, null, signupCallback);
}

private void confirmUser()
{
// Callback handler for confirmSignUp API
GenericHandler confirmationCallback = new GenericHandler() {

@Override
public void onSuccess() {
// User was successfully confirmed
Log.d("myCognito","Confirmed User Success!");
}

@Override
public void onFailure(Exception exception) {
// User confirmation failed. Check exception for the cause.
Log.d("myCognito","Confirmed User faileure :(");
}
};
}
}

我再次对如何创建此类感到困惑,当我使用移动中心时,示例应用程序中的代码到处都是。

最佳答案

试试这个文档 Amazon Cognito Credentials Provider

在 Mobile hub 中查找此文件 CognitoUserPoolsSignInProvider

它包含登录工作原理的所有详细信息

下面是身份验证处理程序(我评论了一些内容以消除错误)

private AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
@Override
public void onSuccess(final CognitoUserSession userSession, final CognitoDevice newDevice) {
Log.i(LOG_TAG, "Logged in. " + userSession.getIdToken());

cognitoUserSession = userSession;

if (null != resultsHandler) {
ViewHelper.showDialog(activity, activity.getString(title_activity_sign_in),
activity.getString(login_success) + " " + userSession.getIdToken());

resultsHandler.onSuccess(CognitoUserPoolsSignInProvider.this);
}

initializedLatch.countDown();
}

@Override
public void getAuthenticationDetails(
final AuthenticationContinuation authenticationContinuation, final String userId) {

if (null != username && null != password) {
final AuthenticationDetails authenticationDetails = new AuthenticationDetails(
username,
password,
null);

authenticationContinuation.setAuthenticationDetails(authenticationDetails);
authenticationContinuation.continueTask();
}

initializedLatch.countDown();
}

@Override
public void getMFACode(final MultiFactorAuthenticationContinuation continuation) {
multiFactorAuthenticationContinuation = continuation;

//todo uncomment it
/* final Intent intent = new Intent(context, MFAActivity.class);
activity.startActivityForResult(intent, MFA_REQUEST_CODE);*/
}

@Override
public void authenticationChallenge(final ChallengeContinuation continuation) {
throw new UnsupportedOperationException("Not supported in this sample.");
}

@Override
public void onFailure(final Exception exception) {
Log.e(LOG_TAG, "Failed to login.", exception);

if (null != resultsHandler) {
ViewHelper.showDialog(activity, activity.getString(R.string.title_activity_sign_in),
"Failed" + " " + exception);
// activity.getString( //todo uncomment it) + " " + exception);

resultsHandler.onError(CognitoUserPoolsSignInProvider.this, exception);
}

initializedLatch.countDown();
}
};

这是 onClick 监听器

@Override
public View.OnClickListener initializeSignInButton(final Activity signInActivity,
final View buttonView,
final IdentityManager.SignInResultsHandler resultsHandler) {

this.activity = signInActivity;
this.resultsHandler = resultsHandler;

// User Pools requires sign in with the username or verified channel.
// Mobile Hub does not set up email verification because it requires SES verification.
// Hence, prompt customers to login using the username or phone number.
final EditText emailField = (EditText) activity.findViewById(EDIT_TEXT_USERNAME_ID);
emailField.setHint(R.string.button_text_sign_in);


final View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
username = ViewHelper.getStringValue(activity, EDIT_TEXT_USERNAME_ID);
password = ViewHelper.getStringValue(activity, EDIT_TEXT_PASSWORD_ID);

final CognitoUser cognitoUser = cognitoUserPool.getUser(username);

cognitoUser.getSessionInBackground(authenticationHandler);
}
};

buttonView.setOnClickListener(listener);
return listener;
}

关于android - 如何在 android 中设置 Cognito 身份池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41204187/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com