通过文档似乎没有明确的方法来做到这一点。创建用户池,然后在Cognito中针对用户池创建提供程序后,如何验证用户名和密码?
我发现了这个sample,但看起来密码是在一个单独的数据库中管理而不是在Cognito中。
答案 0 :(得分:0)
我假设您正在使用适用于Android的移动SDK,并且您已完成所有设置。首先,您需要连接到用户池:
CognitoUserPool userPool = new CognitoUserPool(
context, userPoolId, clientId, clientSecret);
然后,选择要进行身份验证的用户:
CognitoUser user = userPool.getUser(userId);
然后,写下authentication handler。当(如果)需要用户名和密码时,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 */
};
最后,尝试获得一个新会话并给你的处理程序。
user.getSession(handler);
如果一切顺利,您现在应该有一个有效令牌的会话。
此示例基于developer guide,其中还包含注册新用户,注销等示例。
答案 1 :(得分:0)
如果您有用户池,则应该针对用户池进行身份验证。请参阅http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html。
对于后端,您可以使用以下内容:
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);
辅助功能:
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);
}
}
如果您计划跨提供商聚合身份,则只需要联合身份池。在这种情况下,您仍然需要对用户池进行身份验证,并使用经过身份验证的用户ID来识别身份池。