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('=', '');
}
}
user3463289 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.