简体   繁体   English

用户身份池使用Amazon Cognito对用户进行身份验证-Java SDK

[英]User Identity Pool Authenticate user with Amazon Cognito - Java SDK

It doesn't seem through the documentation that there is a clear way to do this. 在文档中似乎没有明确的方法可以执行此操作。 After creating a user pool and then creating a provider in Cognito against the user pool, how do I go about authenticating a username and password? 创建用户池,然后在Cognito中针对用户池创建提供程序之后,如何验证用户名和密码?

I found this sample , but it looks like passwords are managed in a separate database instead of in Cognito. 我找到了此示例 ,但看起来密码是在单独的数据库中而不是在Cognito中管理的。

I'm assuming you're using the Mobile SDK for Android and you have everything set up. 我假设您正在使用Android的Mobile SDK,并且已完成所有设置。 First, you will want to connect to the user pool: 首先,您将要连接到用户池:

CognitoUserPool userPool = new CognitoUserPool(
                             context, userPoolId, clientId, clientSecret);

Then, pick the user you want to authenticate: 然后,选择要验证的用户:

CognitoUser user = userPool.getUser(userId);

Then, write the authentication handler . 然后,编写身份验证处理程序 Cognito will call into your code when (if) it needs a username and a password, rather than you calling it. 如果(如果需要)用户名和密码,而不是您调用它,Cognito将调用您的代码。

AuthenticationHandler handler = new AuthenticationHandler {
    @Override
    public void onSuccess(CognitoUserSession userSession) {
        // Authentication was successful, the "userSession" will have the current valid tokens
    }

    @Override
    public void getAuthenticationDetails(final AuthenticationContinuation continuation, final String userID) {
        // User authentication details, userId and password are required to continue.
        // Use the "continuation" object to pass the user authentication details

        // After the user authentication details are available, wrap them in an AuthenticationDetails class
        // Along with userId and password, parameters for user pools for Lambda can be passed here
        // The validation parameters "validationParameters" are passed in as a Map<String, String>
        AuthenticationDetails authDetails = new AuthenticationDetails(userId, password, validationParameters);

        // Now allow the authentication to continue
        continuation.setAuthenticationDetails(authDetails);
        continuation.continueTask();
    }

    /* Handle 2FA, challenges, etc as needed */
};

Finally, try to get a new session and give your handler. 最后,尝试获取一个新会话并提供给您的处理程序。

user.getSession(handler);

If all goes well, you should now have a session with valid tokens. 如果一切顺利,那么您现在应该使用有效令牌进行会话。

This example is based on the developer guide which also has examples for registering new users, signing out, and so on. 此示例基于开发人员指南 ,该指南也包含用于注册新用户,注销等的示例。

If you have a user pool, you should be authenticating against the user pool. 如果您有用户池,则应该针对用户池进行身份验证。 See http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html . 请参阅http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html

For the back-end, you'd use something like this: 对于后端,您将使用以下方法:

Map<String, String> params = new HashMap<>();
params.put("USERNAME", userId);
params.put("SECRET_HASH", calculateSecretHash(userId));
params.put("PASSWORD", rawPassword);

AdminInitiateAuthRequest request = new AdminInitiateAuthRequest()
    .withUserPoolId("YOUR_USER_POOL_ID")
    .withClientId("YOUR_USER_POOL_APP_CLIENT_ID")
    .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
    .withAuthParameters(params);

AWSCognitoIdentityProvider identityProvider = AWSCognitoIdentityProviderClientBuilder.standard()
        .withCredentials(credentialsProvider)
        .withRegion(Regions.US_WEST_2)
        .build();
AdminInitiateAuthResult result = identityProvider.adminInitiateAuth(request);

Helper function: 辅助功能:

private String calculateSecretHash(@Nonnull String userName) {

  SecretKeySpec signingKey = new SecretKeySpec(m_clientSecret.getBytes(StandardCharsets.UTF_8), HmacAlgorithms.HMAC_SHA_256.toString());
  try {
    Mac mac = Mac.getInstance(HmacAlgorithms.HMAC_SHA_256.toString());
    mac.init(signingKey);
    mac.update(userName.getBytes(StandardCharsets.UTF_8));
    byte[] rawHmac = mac.doFinal(m_clientId.getBytes(StandardCharsets.UTF_8));
    return Base64.encodeBase64String(rawHmac);

  } catch (Exception ex) {
    throw new PgkbRuntimeException("Error calculating secret hash", ex);
  }
}

You only need the federated identity pool if you plan on aggregating identity across providers. 仅当计划跨提供程序聚合身份时,才需要联合身份池。 In this case, you would still need to authenticate against the user pool, and use the authenticated user's id against the identity pool. 在这种情况下,您仍然需要针对用户池进行身份验证,并针对身份池使用经过身份验证的用户ID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Java将用户注册到Amazon Cognito身份用户池 - How to register users to Amazon Cognito identity user pool by using Java 如何使用适用于Java的Amazon Cognito身份SDK访问用户池 - How to Access User Pools using the Amazon Cognito Identity SDK for Java Amazon Cognito开发人员使用Java SDK验证身份 - Amazon Cognito developer authenticated identity with Java SDK JAVA- AWS Cognito - 检查 Cognito 用户池中是否存在用户 - JAVA- AWS Cognito -Check if a user exists in Cognito User pool 适用于通过Cognito用户池为Oauth客户端凭据流身份验证提供服务的AWS Java SDK吗? - AWS Java SDK for service to service Oauth client credentential flow authentication with Cognito user pool? Cognito 用户池:在 aws cognito java sdk 中 accessToken 过期后,如何使用 refreshToken 获取新的 accessToken? - Cognito user pool: How to use refreshToken to get new accessToken after accessToken gets expired in aws cognito java sdk? 如何配置 AWS 用户认知身份验证流程以在 Java sdk 后端生成身份令牌、访问令牌? - How to configure AWS user cognito authentication flow for generating identity token,access token in Java sdk backend? Amazon Cognito 中的用户角色 - User Roles in Amazon Cognito 如何通过Java API使用AWS Cognito对用户进行身份验证 - How to authenticate user using AWS Cognito via Java API Java:未经授权执行sts:AssumeRoleWithWebIdentity认知用户池 - Java:Not authorized to perform sts:AssumeRoleWithWebIdentity cognito user pool
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM