Files
FlutterUnit/lib/app/utils/http_utils/token_interceptor.dart
2022-03-26 18:10:17 +08:00

29 lines
681 B
Dart

import 'package:dio/dio.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
const String _kTokenKey = 'Authorization';
const String _kTokenPrefix = 'Bearer ';
class TokenInterceptors<T> extends InterceptorsWrapper {
String token;
TokenInterceptors({this.token = ''});
void Function()? onTokenDisabled;
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
if (token != '') {
bool disable = JwtDecoder.isExpired(token);
if (disable) {
onTokenDisabled?.call();
}
}
if (token.isNotEmpty) {
options.headers[_kTokenKey] = '$_kTokenPrefix$token';
}
return handler.next(options);
}
}