Unable to get a valid Accesstoken from Azure AD on Flutter Windows Desktop

I’m working on a Flutter application that uses OAuth2 for authentication with Microsoft. I’m trying to implement the authentication flow using a WebView, but I’m encountering some issues. Below is my current implementation.

How can I obtain a signature verified accesstoken in Flutter Windows Desktop app?

Steps to reproduce
Put AD credentials on the variables
Run the sample app
then copy the accesstoken from console logs
then go to jwt.io to validate token

I noticed is that the audience in the token is the Microsoft graph id not the registered app id.

expected result is I will get a valid token and audience is the registered app in AD when validating it in JWT.io and aud will be the registered app in azure when checking it in jwt.ms

import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:desktop_webview_window/desktop_webview_window.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final clientId = '<CLIENT ID HERE>';
  final redirectUri = '<REDIRECT URI HERE>';
  final scope = '<SCOPES HERE>';
  final tenantId = '<TENANT ID HERE>';
  final tokenEndPoint =
      'https://login.microsoftonline.com/<TENANT ID HERE>/oauth2/v2.0/token';
  static const secret = '<CLIENT SECRET HERE>';
  static String? codeVerifier;
  static String? accessToken;
  static String? authCode;

  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Windows Webview Login'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            authCode = await authenticate();
            await exchangeAuthCodeForToken(authCode);
          },
          child: const Text('Open Webview'),
        ),
      ),
    );
  }

  /// Initiates the authentication process by opening a WebView for the user to
  /// log in and authorize the application. It handles the redirection to capture
  /// the authorization code from the URL.
  Future<String?> authenticate() async {
    final codeCompleter = Completer<String?>();
    codeVerifier = generateCodeVerifier();
    final codeChallenge = await generateCodeChallenge(codeVerifier);

    final targetUrl = Uri.https(
      'login.microsoftonline.com',
      '/$tenantId/oauth2/v2.0/authorize',
      {
        'response_type': 'code',
        'client_id': clientId,
        'redirect_uri': redirectUri,
        'code_challenge': codeChallenge,
        'code_challenge_method': 'S256',
        'response_mode': 'query',
        'scope': scope,
      },
    ).toString();

    print(targetUrl);

    final webview = await WebviewWindow.create(
      configuration: const CreateConfiguration(
        titleBarHeight: 0,
        windowWidth: 720,
        windowHeight: 640,
        title: 'Login',
      ),
    );

    webview
      ..addOnUrlRequestCallback((url) async {
        if (url.startsWith(redirectUri)) {
          final uri = Uri.parse(url);
          completeWithAuthCodeUrl(uri, codeCompleter);
        }
      })
      ..onClose.whenComplete(() {
        if (!codeCompleter.isCompleted) codeCompleter.complete(null);
      })
      ..launch(targetUrl);

    final result = await codeCompleter.future;
    webview.close();
    return result;
  }

  /// Processes the URL to extract the authorization code or error information.
  void completeWithAuthCodeUrl(
    Uri url,
    Completer<String?> completer,
  ) {
    if (url.queryParameters.containsKey('code')) {
      completer.complete(url.queryParameters['code'].toString());
    } else if (url.queryParameters.containsKey('error_subcode') &&
        url.queryParameters['error_subcode'] == 'cancel') {
      completer.complete(null);
    }
  }

  /// Exchanges the authorization code for an access token by making a POST request
  /// to the token endpoint. This method also prints out debug information about the
  /// request and response.
  Future<String?> exchangeAuthCodeForToken(
    String? code,
  ) async {
    print('exchangeAuthCodeForToken');
    print(codeVerifier);

    final response = await http.post(
      Uri.parse(tokenEndPoint),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: {
        'grant_type': 'authorization_code',
        'client_id': clientId,
        'client_secret': secret,
        'redirect_uri': redirectUri,
        'code': code,
        'code_verifier': codeVerifier,
      },
    );

    if (response.statusCode == 200) {
      final responseData = json.decode(response.body);
      accessToken = responseData['access_token'];
      final idToken = responseData['id_token'];

      print('Request: ${response.request}');
      print('Access Token: $accessToken');
      print('idToken: $idToken');

      return accessToken;
    } else {
      print(response.request);
      print(response.body);
      print(response.reasonPhrase);
      print(response.statusCode.toString());
      return null;
    }
  }

  /// Generates a code verifier used in the PKCE (Proof Key for Code Exchange) flow.
  /// This is a random string used to secure the authorization process.
  String generateCodeVerifier() {
    final random = Random.secure();
    final bytes = List<int>.generate(43, (i) => random.nextInt(255));
    return base64Url.encode(bytes).replaceAll('=', '');
  }

  /// Generates a code challenge derived from the code verifier. This challenge
  /// is sent to the authorization server to verify that the authorization code
  /// exchange request is coming from the same client that initiated the request.
  Future<String> generateCodeChallenge(String? codeVerifier) async {
    final bytes = utf8.encode(codeVerifier!);
    final digest = sha256.convert(bytes);
    return base64Url.encode(digest.bytes).replaceAll('=', '');
  }
}

New contributor

user3463289 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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