aws-amplify / amplify-flutter

A declarative library with an easy-to-use interface for building Flutter applications on AWS.
https://docs.amplify.aws
Apache License 2.0
1.31k stars 242 forks source link

Amplify.Auth.getCurrentUser() returns AuthUser with incorrect username when using email based auth #3311

Open jniemer opened 1 year ago

jniemer commented 1 year ago

Description

When adding Cognito auth to a project, if email based sign-in is chosen then Amplify.Auth.getCurrentUser() returns an AuthUser that contains the user ID in both userId and username attributes. Expectation would be that username would contain the email address.

Categories

Steps to Reproduce

  1. Configure Amplify Auth (amplify add auth) to use email based authentication.
  2. Sign-up, confirm and sign-in user
  3. Call Amplify.Auth.getCurrentUser().

Screenshots

No response

Platforms

Flutter Version

3.10.5

Amplify Flutter Version

1.2.0

Deployment Method

Amplify CLI

Schema

No response

dnys1 commented 1 year ago

Hi @jniemer - this is indeed confusing and I apologize for the poor DX here. The username field represents the username assigned by Cognito. In the case of email/phone number alias, Cognito considers the "username" of the user to be the user ID, which is why that is mirrored in that field.

The reason for this is two-fold:

In Amplify Flutter v1, we introduced a new field to the AuthUser which tracks the username value used to sign in. This will exactly match whatever was passed to Amplify.Auth.signIn and, in your case, would be the email of the user.

Here is how to use that API:

final authUser = await Amplify.Auth.getCurrentUser();
final username = switch (authUser.signInDetails) {
  // API-based login means calling the `Amplify.Auth.signIn` API
  CognitoSignInDetailsApiBased(:final username) => username,

  // Otherwise, fallback to the value assigned by Cognito
  _ => authUser.username,
};