Allow user to simply select an account rather than having to type in their Microsoft credentials everytime (Flutter, MSAL, AAD_OAUTH)

I was curious how I would be able to allow a user that just signed out of my app to click the Sign In button and have a screen like below appear.

When a user signs out of my app, it requires them to have to re-enter their Microsoft credentials from scratch, whereas the app that I’m trying to mimic has somehow stored your previously signed in accounts and remembered as pictured above.

I’m writing my app using Flutter and the package for authentication that I’m using is aad_oauth and this is what I have for the configuration of my AadOauth instance.

auth_service.dart

static final Config config = Config(
    tenant: '...',
    clientId: '...',
    scope: "${dotenv.env['AppScope']!} openid profile offline_access user.read",
    redirectUri: (Platform.isAndroid)
        ? dotenv.env['androidRedirectUri']!
        : dotenv.env['iOSRedirectUri'],
    navigatorKey: navigatorKey,
    // webUseRedirect: true, // default is false - on web only, forces a redirect flow instead of popup auth
    loader: const Center(child: CircularProgressIndicator()),
    // postLogoutRedirectUri: 'http://your_base_url/logout', //optional
  );

  final AadOAuth oauth = AadOAuth(config);
class AuthService extends ChangeNotifier {
  // TODO: Should move the clientId + tenantId to .env file?
  static final Config config = Config(
    tenant: '...',
    clientId: '...',
    scope: "${dotenv.env['AppScope']!} openid profile offline_access user.read",
    redirectUri: (Platform.isAndroid)
        ? dotenv.env['androidRedirectUri']!
        : dotenv.env['iOSRedirectUri'],
    navigatorKey: navigatorKey,
    // webUseRedirect: true, // default is false - on web only, forces a redirect flow instead of popup auth
    loader: const Center(child: CircularProgressIndicator()),
    // postLogoutRedirectUri: 'http://your_base_url/logout', //optional
  );

  final AadOAuth oauth = AadOAuth(config);

  bool _isLoadingUser = true;
  bool get isLoadingUser => _isLoadingUser;
  set setIsLoadingUser(bool value) {
    _isLoadingUser = value;
    notifyListeners();
  }

  bool _isAuthenticated = false;
  bool get isAuthenticated => _isAuthenticated;

  AuthService();

  Future<void> initializeAuthService() async {
    try {
      if (await hasCachedAccountInformation()) {
        log('User is already authenticated');
        await oauth.refreshToken();
        _isAuthenticated = true;
      } else {
        log('User is not authenticated');
      }
    } catch (e) {
      log('Error initializing AuthService: $e');
    } finally {
      _isLoadingUser = false;
      notifyListeners();
    }
  }

  // Changed to Future<void>, see: https://www.reddit.com/r/dartlang/comments/maxl6y/futurevoid_versus_void_for_async_function_return/
  Future<void> login() async {
    final result = await oauth.login();
    result.fold(
      (l) => log(l.toString()),
      (r) => log('Logged in successfully, your access token: $r'),
    );
    var accessToken = await oauth.getAccessToken();
    if (accessToken != null) {
      log('Access token: $accessToken'); // TODO: Delete?
      _isLoadingUser = false;
      _isAuthenticated = true;
      notifyListeners();
    }
  }

  Future<void> logout() async {
    try {
      log('Logging out'); // TODO: Delete
      await oauth.logout();
      _isAuthenticated = false;
      notifyListeners();
    } catch (e) {
      log('Error logging out: ${e.toString()}');
    }
  }

  Future<bool> hasCachedAccountInformation() async {
    var hasCachedAccountInformation = await oauth.hasCachedAccountInformation;
    log('HasCachedAccountInformation: $hasCachedAccountInformation'); // TODO: Delete
    return hasCachedAccountInformation;
  }

  Future<String?> getCachedAccessToken() async {
    var accessToken = await oauth.getAccessToken();
    log('Got Access token: $accessToken'); // TODO: Delete
    return accessToken;
  }

  refreshToken() async {
    return await oauth.refreshToken();
  }
}

auth_gate.dart (file that shows the Sign in page)

class AuthGate extends StatelessWidget {
  AuthGate({super.key});

  ...

  @override
  Widget build(BuildContext context) {
    ...
      // User is not authenticated
      return LayoutBuilder(builder: (context, constraints) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ...
              ElevatedButton(
                onPressed: () async {
                  await showAlertDialog(
                      context, authService, isMobileWidth);
                },
                child: Text(
                  'SIGN IN',
                  style: isMobileWidth
                      ? primaryButtonText
                      : primaryButtonText.copyWith(
                          fontSize: tabletFontSize,
                        ),
                ),
              ),
            ],
        });
  }

  showAlertDialog(
    ...
    // set up the buttons
    Widget cancelButton = TextButton(
      child: Text(
        "Cancel",
        style: bodyRegular.copyWith(
            fontSize: isMobileWidth ? mobileFontSize : tabletFontSize),
      ),
      onPressed: () => Navigator.of(context).pop(), // dismiss dialog,
    );
    Widget continueButton = TextButton(
      child: Text(
        "Continue",
        style: bodyRegular.copyWith(
            fontSize: isMobileWidth ? mobileFontSize : tabletFontSize),
      ),
      onPressed: () async {
        authService.setIsLoadingUser = true;
        Navigator.of(context).pop(); // dismiss dialog
        await authService.login();
        authService.setIsLoadingUser = false;
      },
    );

    // Android Alert Dialog
    AlertDialog androidAlert = AlertDialog(
      title: Text(
        alertDialogTitle,
        style: bodyRegular.copyWith(
          fontSize: isMobileWidth
              ? mobileDialogTitleFontSize
              : tabletDialogTitleFontSize,
        ),
      ),
      content: Text(
        alertDialogContent,
        style: bodyRegular.copyWith(
          fontSize: isMobileWidth
              ? mobileDialogDescriptionFontSize
              : tabletDialogDescriptionFontSize,
        ),
      ),
      actions: [
        cancelButton,
        continueButton,
      ],
    );

    // iOS Alert Dialog
    CupertinoAlertDialog iOSAlert = CupertinoAlertDialog(
      title: Text(
        alertDialogTitle,
        style: bodyRegular.copyWith(
          fontSize: isMobileWidth
              ? mobileDialogTitleFontSize
              : tabletDialogTitleFontSize,
        ),
      ),
      content: Text(
        alertDialogContent,
        style: bodyRegular.copyWith(
          fontSize: isMobileWidth
              ? mobileDialogDescriptionFontSize
              : tabletDialogDescriptionFontSize,
        ),
      ),
      actions: [
        cancelButton,
        continueButton,
      ],
    );

    // show the dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        if (Platform.isIOS) {
          return iOSAlert;
        } else {
          return androidAlert;
        }
      },
    );
  }
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật