如何在Android中使用AWS Cognito实现用户认证及代码转换求助
Hey there! Let's sort this out for you. The Android code snippet you're using right now relies on CognitoCachingCredentialsProvider, which is designed for federated identity pools (to fetch AWS service credentials), not directly authenticating against a Cognito User Pool to grab access/id tokens. Here's the correct approach to implement User Pool authentication and retrieve those tokens you need:
Step 1: Add Required Dependencies
First, make sure you have the AWS Cognito SDK dependencies in your app-level build.gradle file (use the latest version available):
dependencies { implementation 'com.amazonaws:aws-android-sdk-cognitoidentityprovider:2.42.0' implementation 'com.amazonaws:aws-android-sdk-cognito:2.42.0' }
Step 2: Implement User Pool Authentication
Replace your existing code with this complete implementation to authenticate users and retrieve tokens:
// Initialize your Cognito User Pool with your pool details CognitoUserPool userPool = new CognitoUserPool( getApplicationContext(), "us-east-1_TcoKGbf7n", // Your User Pool ID from JS code "4pe2usejqcdmhi0a25jp4b5sh3", // Your Client ID from JS code null, // Leave null if you don't have a Client Secret for your app client Regions.US_EAST_1 // Region where your User Pool is hosted ); // Create authentication details with username and password AuthDetails authDetails = new AuthDetails( "username", // User's username "password", // User's password null, // SRP auth details (leave null for simple username/password auth) null ); // Get the CognitoUser instance for the user CognitoUser cognitoUser = userPool.getUser("username"); // Initiate background authentication cognitoUser.authenticateUserInBackground(authDetails, new AuthenticationHandler() { @Override public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) { // ✅ Here's where you access your tokens! String accessToken = userSession.getAccessToken().getJWTToken(); String idToken = userSession.getIdToken().getJWTToken(); String refreshToken = userSession.getRefreshToken().getToken(); // Log or use the tokens as needed (e.g., pass to API Gateway) Log.d("CognitoAuth", "Access Token: " + accessToken); Log.d("CognitoAuth", "ID Token: " + idToken); // If you need to federate with a Cognito Identity Pool (like your JS code did), // set the ID token in the logins map for your credentials provider: Map<String, String> logins = new HashMap<>(); // The key follows this format: "cognito-idp.<region>.amazonaws.com/<userPoolId>" logins.put("cognito-idp.us-east-1.amazonaws.com/us-east-1_TcoKGbf7n", idToken); CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider( getApplicationContext(), "dqdwrqw*******", // Your Identity Pool ID from JS code Regions.US_EAST_1 // Region of your Identity Pool ); credentialsProvider.setLogins(logins); // Now you can use credentialsProvider to get AWS service credentials } @Override public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) { // For simple username/password auth, just pass the existing auth details authenticationContinuation.setAuthenticationDetails(authDetails); authenticationContinuation.continueTask(); } @Override public void getMFACode(MultiFactorAuthenticationContinuation continuation) { // Handle MFA if your User Pool requires it: // Prompt the user for their MFA code, then call: // continuation.setMfaCode(userProvidedCode); // continuation.continueTask(); } @Override public void authenticationChallenge(ChallengeContinuation continuation) { // Handle additional challenges (e.g., new password required for first-time login) // Example: if challenge is "NEW_PASSWORD_REQUIRED", prompt user for new password and set it via continuation } @Override public void onFailure(Exception exception) { // ❌ Handle authentication failures (e.g., wrong password, user not found) Log.e("CognitoAuth", "Authentication failed: " + exception.getMessage()); } });
Why Your Original Code Didn't Work
Your initial CognitoCachingCredentialsProvider.setLogins() call was passing raw username/password, but this method expects valid identity provider tokens (like the ID Token from your User Pool) to federate identities. It doesn't handle direct User Pool authentication itself.
内容的提问来源于stack exchange,提问作者jason




