getAccessToken method
Retrieves an access token from Azure AD using the client credentials flow.
This function:
- Sends a POST request to Azure Active Directory (AAD) token endpoint
using the provided
tenantId,clientId,clientSecret, andresource. - If the request is successful (HTTP 200), it returns the
access_token. - If the request fails, it logs the error message and returns null.
Returns:
- A
Stringcontaining the access token if successful. nullif the request fails.
Implementation
Future<String?> getAccessToken() async {
final url = Uri.parse(
'https://login.microsoftonline.com/$tenantId/oauth2/token',
);
final response = await http.post(
url,
body: {
'grant_type': 'client_credentials',
'client_id': clientId,
'client_secret': clientSecret,
'resource': resource,
},
);
if (response.statusCode == 200) {
return json.decode(response.body)['access_token'];
} else {
print("❌ Failed to get token: ${response.body}");
return null;
}
}