Skip to main content

Flutter

Official

Cross-platform authentication for Flutter apps.

Accessing Protected APIs

~3 min

Use `ThunderIDProvider.of(context).client.getAccessToken()` to retrieve the current access token. The SDK automatically refreshes the token if it has expired. Pass the token as a `Bearer` credential in your HTTP requests.

Accessing Protected APIs

1

Using `http` Package

dart

Future<Map<String, dynamic>> fetchUserData(BuildContext context) async {
  final thunder = ThunderIDProvider.of(context);
  final token = await thunder.client.getAccessToken();

  final response = await http.get(
    Uri.parse('https://api.example.com/user'),
    headers: {
      'Authorization': 'Bearer $token',
      'Content-Type': 'application/json',
    },
  );

  if (response.statusCode == 200) {
    return jsonDecode(response.body) as Map<String, dynamic>;
  }

  throw Exception('Request failed: ${response.statusCode}');
}
2

Using `dio` with an Interceptor

Add [dio](https://pub.dev/packages/dio) to your `pubspec.yaml`:

yaml
dependencies:
  dio: ^5.4.0
3

Token Expiry and Refresh

`getAccessToken()` automatically refreshes the access token using the stored refresh token if the current token is expired. If the refresh token is also expired, it throws `IAMException` with code `IAMErrorCode.sessionExpired`.

dart
try {
  final token = await thunder.client.getAccessToken();
  // Use token...
} on IAMException catch (e) {
  if (e.code == IAMErrorCode.sessionExpired) {
    // Session has fully expired. Sign the user out.
    await thunder.client.signOut();
    await thunder.refresh();
  }
}
4

Checking Sign-In State Before Requests

Check `thunder.isSignedIn` before making API calls in widgets to avoid unnecessary network requests:

dart
@override
Widget build(BuildContext context) {
  final thunder = ThunderIDProvider.of(context);

  return SignedIn(
    child: FutureBuilder(
      future: fetchUserData(context),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        }
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return Text('Hello, ${snapshot.data}');
      },
    ),
    fallback: const AuthScreen(),
  );
}
ThunderID LogoThunderID Logo

Product

DocsAPIsSDKs
© Copyright Linux Foundation Europe.For web site terms of use, trademark policy and other project policies please see https://linuxfoundation.eu/en/policies.