Cannot retrieve JWT/access tokens from Amplify Auth in flutter for use in API authorization

34 views Asked by At
import 'dart:async';
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import '../amplifyconfiguration.dart';
import 'package:amplify_flutter/amplify_flutter.dart';

class LogInService {
  LogInService() {
    _configureAmplify();
  }

  Future<void> _configureAmplify() async {
    try {
      AmplifyAuthCognito auth = AmplifyAuthCognito();
      await Amplify.addPlugin(auth);

      // call Amplify.configure to use the initialized categories in your app
      await Amplify.configure(amplifyconfig);
    } on Exception catch (e) {
      safePrint('An error occurred configuring Amplify: $e');
    }
  }

  Future<bool> signInWithWebUI() async {
    try {
      final result = await Amplify.Auth.signInWithWebUI();
      final creds = await Amplify.Auth.fetchAuthSession();
      safePrint('Sign in result: $creds');
      if (creds.isSignedIn) {
        fetchCognitoAuthSession();
        return true;
      }
      else {
        return false;
      }
    } on AuthException catch (e) {
      safePrint('Error signing in: ${e.message}');
      return false;
    }
  }

  Future<void> fetchCognitoAuthSession() async {
    try {
      final cognitoPlugin = Amplify.Auth.getPlugin(AmplifyAuthCognito.pluginKey);
      final result = await cognitoPlugin.fetchAuthSession();
      final accessToken = result.
      final identityId = result.identityIdResult.value;
      safePrint("Current user's identity ID: $identityId");
    } on AuthException catch (e) {
      safePrint('Error retrieving auth session: ${e.message}');
    }
  }

  Future<void> signOutWithWebUI() async {
    try {
      await Amplify.Auth.signOut();
      safePrint("Signed out successfully");
    } on AuthException catch (e) {
      safePrint(e.message);
    }
  }
}

After the user is successfully signed in, I am trying to get access to identityId and JWT to use for API Authorization in Future<void> fetchCognitoAuthSession() , but I just get Error retrieving auth session: The AWS credentials could not be retrieved.

With the await Amplify.Auth.fetchAuthSession(); the following messages are returned Sign in result: { I/flutter (11660): "isSignedIn": true, I/flutter (11660): "userSub": "AWSSuccessResult<String, AuthException> {\n \"value\": \"<some value that is removed>\"\n}", I/flutter (11660): "userPoolTokens": "AWSSuccessResult<CognitoUserPoolTokens, AuthException> {\n \"value\": {\n \"signInMethod\": \"hostedUi\",\n \"accessToken\": \" <some access token that is removed>

The identity ID and JWT is never accessable with my solution can you someone explain why this dont work and how i can solve it.

0

There are 0 answers