onRequest method

  1. @override
void onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)
override

Intercepts outgoing requests to check for token expiry (preemptive strategy).

If isPreemptivelyRefreshBeforeExpiry is true and the JWT is expired:

  • Attempts to refresh the token before sending the request
  • If refresh succeeds, continues with the updated token
  • If refresh fails and auth is required, rejects the request
  • If refresh fails and auth is not required, removes the auth header and continues

Paths listed in AuthOptions.ignoreAuthForPaths bypass token checking.

Implementation

@override
void onRequest(RequestOptions options, handler) async {
  if (isPreemptivelyRefreshBeforeExpiry &&
      !authOptions.ignoreAuthForPaths.contains(options.path)) {
    try {
      final bearer = options.headers[RestApiClientKeys.authorization];
      final jwt = bearer != null
          ? (bearer as String).replaceAll('Bearer ', '')
          : '';

      if (jwt.isEmpty) {
        handler.next(options);
      } else {
        final isExpired = JwtDecoder.isExpired(jwt);

        if (isExpired) {
          await authHandler.refreshTokenCallback(options, handler);
        } else {
          handler.next(options);
        }
      }
    } catch (e) {
      if (_isAuthRequired(options)) {
        handler.reject(DioException(requestOptions: options, error: e));
      } else {
        // Auth not required - remove invalid token and continue without auth
        options.headers.remove(RestApiClientKeys.authorization);
        handler.next(options);
      }
    }
  } else {
    handler.next(options);
  }
}