how to do a flutter authentication with microsoft for web

I want to authenticate in a webapp at microsoft using flutter. I started using this package: https://pub.dev/packages/aad_oauth

For my Mobile Platforms it works like a charm, but something is not working in my webapp redirecting flow. It opens the microsoft page and after authentiation, i am getting successfully redirected to my app. But when returning, the code that comes after the login is not getting executed. Here is my code

Future<String?> loginUserWithMicrosoft(User user, String adminID) async {
  final Config config = Config(
    tenant: "common",
    clientId: "xxx",
    scope:
        "https://graph.microsoft.com/User.Read https://graph.microsoft.com/Calendars.ReadWrite offline_access",
    redirectUri: "xxx",
    navigatorKey: navigatorKey,
  );

  try {
    final AadOAuth oauth = AadOAuth(config);
    print("Initiating Login");

    final result = await oauth.login();
    print("Login Result: $result");

    return result.fold(
      (l) {
        print("Login Failed: $l");
        return null;
      },
      (r) {
        print("Login Successful: $r");
        if (r.refreshToken != null) {
          updateUserRefreshToken(adminID, user.userID, r.refreshToken!);
        }
        if (r.accessToken != null) {
          updateUserAccessToken(adminID, user.userID, r.accessToken!);
        }
        return r.accessToken;
      },
    );
  } catch (e) {
    print("Error during login: $e");
    return null;
  }
}

The Code: print("Login Result: $result"); is not getting called anymore. It just prints out everything until the login command. The code after is not executed. Consequently i do also not receive any token. In the Documentation it says something like you need to call login a second time. not sure tho in what way, since code after the first login is discarded..

5

I successfully authenticated the Flutter application and obtained the access token using the aad_oauth package in the web app.

main.dart :

import 'package:flutter/material.dart';
import 'login_page.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Azure AD Login',
      navigatorKey: navigatorKey,
      home: LoginPage(navigatorKey: navigatorKey), 
    );
  }
}

login_page.dart :

import 'package:flutter/material.dart';
import 'package:aad_oauth/aad_oauth.dart';
import 'package:aad_oauth/model/config.dart';
import 'home_page.dart';

class LoginPage extends StatelessWidget {
  final GlobalKey<NavigatorState> navigatorKey;
  late final AadOAuth oauth;
  LoginPage({Key? key, required this.navigatorKey}) : super(key: key) {
    final config = Config(
      tenant: "<TenantID>",
      clientId: "<ClientID>",
      scope: "https://graph.microsoft.com/User.Read https://graph.microsoft.com/Calendars.ReadWrite offline_access",
      redirectUri: "http://localhost:8000/",
      webUseRedirect: true,
      navigatorKey: navigatorKey,
    );
    oauth = AadOAuth(config);
  }
  Future<String?> loginUserWithMicrosoft() async {
    try {
      final result = await oauth.login();
      return result.fold(
            (l) {
          print("Login Failed: $l");
          return null;
        },
            (r) {
          print("Login Successful: $r");
          return r.accessToken; 
        },
      );
    } catch (e) {
      print("Error during login: $e");
      return null;
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final accessToken = await loginUserWithMicrosoft();
            if (accessToken != null) {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => HomePage(token: accessToken, oauth: oauth), 
                ),
              );
            } else {
              showError("Login failed or access token is null");
            }
          },
          child: Text('Login with Azure AD'),
        ),
      ),
    );
  }
  void showError(String message) {
    print(message);
  }
}

home_page.dart :

import 'package:flutter/material.dart';
import 'package:aad_oauth/aad_oauth.dart';
import 'login_page.dart';

class HomePage extends StatelessWidget {
  final String token;
  final AadOAuth oauth;
  const HomePage({Key? key, required this.token, required this.oauth}) : super(key: key);
  void logout(BuildContext context) async {
    await oauth.logout();
    print("Logged out");
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => LoginPage(navigatorKey: GlobalKey<NavigatorState>())),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Logged in successfully!nYour access token: $token'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => logout(context),
              child: Text('Logout'),
            ),
          ],
        ),
      ),
    );
  }
}

index.html :

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Flutter AAD OAuth</title>
  <script type="text/javascript" src="https://alcdn.msauth.net/browser/2.13.1/js/msal-browser.min.js" integrity="sha384-2Vr9MyareT7qv+wLp1zBt78ZWB4aljfCTMUrml3/cxm0W81ahmDOC6uyNmmn0Vrc" crossorigin="anonymous"></script>
  <script src="assets/packages/aad_oauth/assets/msalv2.js"></script>
</head>
<body>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

I have added the URL below in the AD app’s redirect URI as a Web, as shown below.

http://localhost:8000/

Output :

I used port 8000 to run the Flutter application as a web app in Chrome.

flutter run -d chrome --web-port 8000

Browser Output :

I successfully logged in by clicking on the Login with Azure AD button as shown below.

I got the access token, as shown below.

1

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