exchangeCodeForToken method

  1. @override
Future<Map<Object?, Object?>?> exchangeCodeForToken({
  1. required String tenantId,
  2. required String clientId,
  3. String? clientSecret,
  4. required String code,
  5. required String redirectUrl,
  6. String? scope,
})
override

Implementation

@override
Future<Map<Object?, Object?>?> exchangeCodeForToken({
  required String tenantId,
  required String clientId,
  String? clientSecret,
  required String code,
  required String redirectUrl,
  String? scope,
}) async {
  final urlString =
      'https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token';
  final url = Uri.parse(urlString);

  final params = <String, String>{
    'client_id': clientId,
    'code': code,
    'redirect_uri': redirectUrl,
    'grant_type': 'authorization_code',
  };

  if (clientSecret != null) {
    params['client_secret'] = clientSecret;
  }
  if (scope != null) {
    params['scope'] = scope;
  }

  try {
    final response = await http.post(
      url,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: params,
    );

    if (response.statusCode == 200) {
      final Map<String, dynamic> jsonObject = jsonDecode(response.body);
      return jsonObject;
    } else {
      throw Exception(
        'Response code: \${response.statusCode}, error: \${response.body}',
      );
    }
  } catch (e) {
    throw Exception('NETWORK_ERROR: \${e.toString()}');
  }
}