refreshOrThrow method
Implementation
Future<void> refreshOrThrow() async {
final refreshToken = MeshagentAuth.current.getRefreshToken();
if (refreshToken == null || refreshToken.isEmpty) {
throw StateError('No refresh token available');
}
final response = await http.post(
_tokenEndpoint,
headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: jsonEncode({
'grant_type': 'refresh_token',
'refresh_token': refreshToken,
'client_id': clientId,
if (clientSecret != null) 'client_secret': clientSecret,
}),
);
if (response.statusCode < 200 || response.statusCode >= 300) {
throw Exception('Failed to refresh token: ${response.statusCode} ${response.body}');
}
final data = jsonDecode(response.body);
final accessToken = data["access_token"];
final newRefreshToken = data["refresh_token"]; // may be absent
final expiresIn = data["expires_in"];
if (accessToken is! String || accessToken.isEmpty) {
throw Exception('Refresh response missing access_token');
}
MeshagentAuth.current.setAccessToken(accessToken);
// Keep old refresh token if server doesn’t rotate.
if (newRefreshToken is String && newRefreshToken.isNotEmpty) {
MeshagentAuth.current.setRefreshToken(newRefreshToken);
}
MeshagentAuth.current.setExpiresIn(expiresIn);
}