fix: API interceptor 增加 token 刷新单飞机制防止并发刷新
This commit is contained in:
@@ -4,11 +4,18 @@ import '../storage/token_storage.dart';
|
||||
class ApiInterceptor extends Interceptor {
|
||||
final TokenStorage tokenStorage;
|
||||
final Dio dio;
|
||||
final Duration refreshFailureCooldown;
|
||||
Future<bool> Function()? onTokenRefresh;
|
||||
Future<bool>? _refreshFuture;
|
||||
DateTime? _refreshBlockedUntil;
|
||||
|
||||
static const _retriedRequestKey = '_auth_retry_once';
|
||||
static const _refreshPathSuffix = '/api/v1/auth/sessions/refresh';
|
||||
|
||||
ApiInterceptor({
|
||||
required this.tokenStorage,
|
||||
required this.dio,
|
||||
this.refreshFailureCooldown = const Duration(seconds: 5),
|
||||
this.onTokenRefresh,
|
||||
});
|
||||
|
||||
@@ -26,22 +33,69 @@ class ApiInterceptor extends Interceptor {
|
||||
|
||||
@override
|
||||
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||||
if (err.response?.statusCode == 401 && onTokenRefresh != null) {
|
||||
final refreshed = await onTokenRefresh!();
|
||||
final requestOptions = err.requestOptions;
|
||||
if (err.response?.statusCode == 401 &&
|
||||
onTokenRefresh != null &&
|
||||
!_shouldSkipRefresh(requestOptions)) {
|
||||
final refreshed = await _refreshTokenSingleflight();
|
||||
if (refreshed) {
|
||||
final token = await tokenStorage.getAccessToken();
|
||||
if (token != null) {
|
||||
err.requestOptions.headers['Authorization'] = 'Bearer $token';
|
||||
final retryHeaders = Map<String, dynamic>.from(requestOptions.headers)
|
||||
..['Authorization'] = 'Bearer $token';
|
||||
final retryExtra = Map<String, dynamic>.from(requestOptions.extra)
|
||||
..[_retriedRequestKey] = true;
|
||||
final retryOptions = requestOptions.copyWith(
|
||||
headers: retryHeaders,
|
||||
extra: retryExtra,
|
||||
);
|
||||
try {
|
||||
final response = await dio.fetch(err.requestOptions);
|
||||
final response = await dio.fetch(retryOptions);
|
||||
handler.resolve(response);
|
||||
return;
|
||||
} on DioException {
|
||||
// Retry failed, proceed with original error
|
||||
// Retry failed, proceed with original error.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
handler.next(err);
|
||||
}
|
||||
|
||||
bool _shouldSkipRefresh(RequestOptions options) {
|
||||
final blockedUntil = _refreshBlockedUntil;
|
||||
if (blockedUntil != null && DateTime.now().isBefore(blockedUntil)) {
|
||||
return true;
|
||||
}
|
||||
return _normalizePath(options.path) == _refreshPathSuffix ||
|
||||
options.extra[_retriedRequestKey] == true;
|
||||
}
|
||||
|
||||
String _normalizePath(String rawPath) {
|
||||
final parsed = Uri.tryParse(rawPath);
|
||||
if (parsed == null) {
|
||||
return rawPath.replaceFirst(RegExp(r'/+$'), '');
|
||||
}
|
||||
final normalized = parsed.path.replaceFirst(RegExp(r'/+$'), '');
|
||||
return normalized.isEmpty ? '/' : normalized;
|
||||
}
|
||||
|
||||
Future<bool> _refreshTokenSingleflight() {
|
||||
final inflight = _refreshFuture;
|
||||
if (inflight != null) {
|
||||
return inflight;
|
||||
}
|
||||
final future = onTokenRefresh!().catchError((_) => false).whenComplete(() {
|
||||
_refreshFuture = null;
|
||||
});
|
||||
_refreshFuture = future;
|
||||
return future.then((refreshed) {
|
||||
if (refreshed) {
|
||||
_refreshBlockedUntil = null;
|
||||
} else {
|
||||
_refreshBlockedUntil = DateTime.now().add(refreshFailureCooldown);
|
||||
}
|
||||
return refreshed;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user