Last active
June 8, 2023 16:54
-
-
Save ehbc221/fcf5240803d68a963418374f59d8b7da to your computer and use it in GitHub Desktop.
An interceptor for JWTs in Flutter, using dio and shared_preferences libraries. Handles retrieving the JWT in shared_preferences (when exists) and adding it to the request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:dio/dio.dart'; | |
import 'package:expenza/config/injectable.dart'; | |
import 'package:expenza/domain/user_preferences.dart'; | |
import 'package:expenza/utils/log.utils.dart'; | |
const String _tag = 'JwtInterceptor'; | |
/// Jwt Interceptor. | |
/// | |
/// This class provides the Jwt from the user's session to the request's header | |
/// authorization if exists. | |
/// | |
/// - author - @ehbc221 | |
/// - version - 1.0.0 | |
/// - last updated - June 8th, 2023 | |
class JwtInterceptor extends Interceptor { | |
@override | |
Future<void> onRequest( | |
RequestOptions options, | |
RequestInterceptorHandler handler, | |
) async { | |
logD(_tag, 'onRequest called.'); | |
// Check if the user has a Jwt in sharedPreferences | |
final String? authToken = getIt<UserPreferences>().getAuthJWT()?.idToken; | |
// Get the token from the user's session | |
if (authToken != null) { | |
final Map<String, String> authorizationHeader = <String, String>{ | |
'Authorization': 'Bearer $authToken' | |
}; | |
// Add Jwt to the request | |
options.headers.addAll(authorizationHeader); | |
} | |
// Call the next interceptor | |
return handler.next(options); | |
} | |
} |
Please note that you can replace the JWT provider (we are using shared_preferences here) with the one you like.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Your can chain this interceptor with others when building your API configuration with dio.