Files
FlutterUnit/lib/app/utils/http_utils/token_interceptor.dart
2021-09-27 09:38:18 +08:00

29 lines
696 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 != null&&token.isNotEmpty) {
options.headers[_kTokenKey] = '$_kTokenPrefix$token';
}
return handler.next(options);
}
}