skip to Main Content

I am building a mobile application with Flutter and AWS. I am using the AWS Cognito user pool to authenticate users in the app. There are types of users in my app, which is the type USER and ADMIN. The Admin users are in an ADMIN user group. After the user is authenticated, I want to get the user group’s ADMIN to a different view.

How to get the user group in Flutter AWS?

2

Answers


  1. Chosen as BEST ANSWER

    I was able to get the user group after decoding the accessToken. The token contains cognito:groups attribute if the user inside a group

     AuthSession authSessions = await Amplify.Auth.fetchAuthSession( options: CognitoSessionOptions(getAWSCredentials: true));
    
        if(authSessions.isSignedIn) {
          final accessToken = (authSessions as CognitoAuthSession).userPoolTokens?.accessToken;
          print("identityId ==>  ${accessToken}");
        }
    

    Docs : https://docs.amplify.aws/lib/auth/access_credentials/q/platform/flutter/


  2. The solution is to get and decode the Jwt Token:

    dart pub add jwt_decode
    
    import 'package:jwt_decode/jwt_decode.dart';
    
    Future<void> fetchUserGroups() async {
      try {
        AuthSession authSessions = await Amplify.Auth.fetchAuthSession(
            options: CognitoSessionOptions(getAWSCredentials: true));
    
        if (authSessions.isSignedIn) {
          final accessToken =
              (authSessions as CognitoAuthSession).userPoolTokens?.accessToken;
          Map<String, dynamic> payload = Jwt.parseJwt(accessToken!);
    
          print(payload);
        }
      } on AuthException catch (e) {
        print(e.message);
      }

    The output:

    D/AWSMobileClient( 3097): Inspecting user state details
    D/AWSMobileClient( 3097): hasFederatedToken: true provider: cognito-idp.eu-central-1.amazonaws.com/eu-central-1_RZyl8shky
    D/AWSMobileClient( 3097): Inspecting user state details
    D/AWSMobileClient( 3097): hasFederatedToken: true provider: cognito-idp.eu-central-1.amazonaws.com/eu-central-1_RZyl8shky
    D/AWSMobileClient( 3097): waitForSignIn: userState:SIGNED_IN
    D/AWSMobileClient( 3097): getCredentials: Validated user is signed-in
    I/flutter ( 3097): {sub: c507e235-5752-46h7-af83-a2c05b436d5d, cognito:groups: [reviewers], iss: https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_RZyl8blsy, client_id: rehacmqlfabslccps0mfbf5gg, origin_jti: 2b13ea50-29ba-4f5c-9708-f13d53f5e9a6, event_id: 836061ff-78ae-4c1b-8b97-771188c328c7, token_use: access, scope: aws.cognito.signin.user.admin, auth_time: 1676172290, exp: 1676201666, iat: 1676198066, jti: 6c7f656c-7729-46fc-8312-4448a8d9217a, username: c507e235-5752-46df-af83-w2c05r536d5d}

    Thanks @Dhanuka

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search