-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix: example of queued_interceptor_csrftoken.dart #2345
Open
seunghwanly
wants to merge
6
commits into
cfug:main
Choose a base branch
from
seunghwanly:fix-queued-interceptor-csrftoken-example-code
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a8871ad
fix: example under misconception
seunghwanly 9fc8bc6
chore: file path
seunghwanly 0c668a3
chore: IDE automation fixes
seunghwanly c550983
chore: IDE automation fixes
seunghwanly 9af8b90
fix: close after used
seunghwanly 4ab72bf
fix: close after used
seunghwanly File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,164 +1,172 @@ | ||
// ignore: dangling_library_doc_comments | ||
/// CSRF Token Example | ||
/// | ||
/// Add interceptors to handle CSRF token. | ||
/// - token update | ||
/// - retry policy | ||
/// | ||
/// Scenario: | ||
/// 1. Client access to the Server by using `GET` method. | ||
/// 2. Server generates CSRF token and sends it to the client. | ||
/// 3. Client make a request to the Server by using `POST` method with the CSRF token. | ||
/// 4. If the CSRF token is invalid, the Server returns 401 status code. | ||
/// 5. Client requests a new CSRF token and retries the request. | ||
import 'dart:developer'; | ||
import 'dart:convert'; | ||
import 'dart:math'; | ||
|
||
import 'package:dio/dio.dart'; | ||
|
||
void main() async { | ||
/// HTML example: | ||
/// ``` html | ||
/// <input type="hidden" name="XSRF_TOKEN" value=${cachedCSRFToken} /> | ||
/// ``` | ||
const String cookieKey = 'XSRF_TOKEN'; | ||
|
||
/// Header key for CSRF token | ||
const String headerKey = 'X-Csrf-Token'; | ||
|
||
String? cachedCSRFToken; | ||
|
||
void printLog( | ||
int index, | ||
String path, | ||
) => | ||
log( | ||
''' | ||
#$index | ||
- Path: '$path' | ||
- CSRF Token: $cachedCSRFToken | ||
''', | ||
name: 'queued_interceptor_csrftoken.dart', | ||
); | ||
|
||
final dio = Dio() | ||
..options.baseUrl = 'https://httpbun.com/' | ||
..interceptors.addAll( | ||
[ | ||
/// Handles CSRF token | ||
QueuedInterceptorsWrapper( | ||
/// Adds CSRF token to headers, if it exists | ||
onRequest: (requestOptions, handler) { | ||
if (cachedCSRFToken != null) { | ||
requestOptions.headers[headerKey] = cachedCSRFToken; | ||
requestOptions.headers['Set-Cookie'] = | ||
'$cookieKey=$cachedCSRFToken'; | ||
} | ||
return handler.next(requestOptions); | ||
}, | ||
|
||
/// Update CSRF token from [response] headers, if it exists | ||
onResponse: (response, handler) { | ||
final token = response.headers.value(headerKey); | ||
|
||
if (token != null) { | ||
cachedCSRFToken = token; | ||
} | ||
return handler.resolve(response); | ||
}, | ||
|
||
onError: (error, handler) async { | ||
if (error.response == null) { | ||
return handler.next(error); | ||
} | ||
|
||
/// When request fails with 401 status code, request new CSRF token | ||
if (error.response?.statusCode == 401) { | ||
try { | ||
final tokenDio = Dio( | ||
BaseOptions(baseUrl: error.requestOptions.baseUrl), | ||
); | ||
|
||
/// Generate CSRF token | ||
/// | ||
/// This is a MOCK REQUEST to generate a CSRF token. | ||
/// In a real-world scenario, this should be generated by the server. | ||
final result = await tokenDio.post( | ||
'/response-headers', | ||
queryParameters: { | ||
headerKey: '94d6d1ca-fa06-468f-a25c-2f769d04c26c', | ||
}, | ||
); | ||
|
||
if (result.statusCode == null || | ||
result.statusCode! ~/ 100 != 2) { | ||
throw DioException(requestOptions: result.requestOptions); | ||
} | ||
|
||
final updatedToken = result.headers.value(headerKey); | ||
if (updatedToken == null) { | ||
throw ArgumentError.notNull(headerKey); | ||
} | ||
|
||
cachedCSRFToken = updatedToken; | ||
|
||
return handler.next(error); | ||
} on DioException catch (e) { | ||
return handler.reject(e); | ||
} | ||
} | ||
}, | ||
), | ||
|
||
/// Retry the request when 401 occurred | ||
QueuedInterceptorsWrapper( | ||
onError: (error, handler) async { | ||
if (error.response != null && error.response!.statusCode == 401) { | ||
final retryDio = Dio( | ||
BaseOptions(baseUrl: error.requestOptions.baseUrl), | ||
); | ||
|
||
if (error.requestOptions.headers.containsKey(headerKey) && | ||
error.requestOptions.headers[headerKey] != cachedCSRFToken) { | ||
error.requestOptions.headers[headerKey] = cachedCSRFToken; | ||
} | ||
|
||
/// In real-world scenario, | ||
/// the request should be requested with [error.requestOptions] | ||
/// using [fetch] method. | ||
/// ``` dart | ||
/// final result = await retryDio.fetch(error.requestOptions); | ||
/// ``` | ||
final result = await retryDio.get('/mix/s=200'); | ||
|
||
return handler.resolve(result); | ||
} | ||
}, | ||
), | ||
], | ||
); | ||
|
||
/// Make Requests | ||
printLog(0, 'initial'); | ||
|
||
/// #1 Access to the Server | ||
final accessResult = await dio.get( | ||
'/response-headers', | ||
final tokenManager = TokenManager(); | ||
|
||
/// Pretend the Server has generated CSRF token | ||
/// and passed it to the client. | ||
queryParameters: { | ||
headerKey: 'fbf07f2b-b957-4555-88a2-3d3e30e5fa64', | ||
}, | ||
final dio = Dio( | ||
BaseOptions( | ||
baseUrl: 'https://httpbun.com/', | ||
), | ||
); | ||
printLog(1, accessResult.realUri.path); | ||
|
||
/// #2 Make a request(POST) to the Server | ||
/// | ||
/// Pretend the token has expired. | ||
/// | ||
/// Then the interceptor will request a new CSRF token | ||
final createResult = await dio.post( | ||
'/mix/s=401/', | ||
|
||
dio.interceptors.add( | ||
QueuedInterceptorsWrapper( | ||
onRequest: (requestOptions, handler) { | ||
print( | ||
''' | ||
[onRequest] ${requestOptions.hashCode} / time: ${DateTime.now().toIso8601String()} | ||
\tPath: ${requestOptions.path} | ||
\tHeaders: ${requestOptions.headers} | ||
''', | ||
); | ||
|
||
/// In case, you have 'refresh_token' and needs to refresh your 'access_token' | ||
/// Make a request for new 'access_token' and update from here | ||
|
||
if (tokenManager.accessToken != null) { | ||
requestOptions.headers['Authorization'] = | ||
'Bearer ${tokenManager.accessToken}'; | ||
} | ||
|
||
return handler.next(requestOptions); | ||
}, | ||
onResponse: (response, handler) { | ||
print(''' | ||
[onResponse] ${response.requestOptions.hashCode} / time: ${DateTime.now().toIso8601String()} | ||
\tStatus: ${response.statusCode} | ||
\tData: ${response.data} | ||
'''); | ||
|
||
return handler.resolve(response); | ||
}, | ||
onError: (error, handler) async { | ||
final statusCode = error.response?.statusCode; | ||
print( | ||
''' | ||
[onError] ${error.requestOptions.hashCode} / time: ${DateTime.now().toIso8601String()} | ||
\tStatus: $statusCode | ||
''', | ||
); | ||
|
||
/// This example only handles '401' status code, | ||
/// The more complex scenario should handle more status codes e.g. '403', '404', etc. | ||
if (statusCode != 401) { | ||
return handler.resolve(error.response!); | ||
} | ||
|
||
/// Consider [dio] can be requested in parallel. | ||
/// | ||
/// To prevent repeated requests to the 'Authentication Server' | ||
/// to update our 'access_token', | ||
/// we can compare with the previously requested 'access_token'. | ||
final requestedAccessToken = | ||
error.requestOptions.headers['Authorization']; | ||
if (requestedAccessToken == tokenManager.accessToken) { | ||
final tokenRefreshDio = Dio() | ||
..options.baseUrl = 'https://httpbun.com/'; | ||
|
||
final response = await tokenRefreshDio.post( | ||
'https://httpbun.com/mix/s=201/b64=${base64.encode( | ||
jsonEncode(AuthenticationServer.generate()).codeUnits, | ||
)}', | ||
); | ||
tokenRefreshDio.close(); | ||
|
||
if (response.statusCode == null || response.statusCode! ~/ 100 != 2) { | ||
return handler.reject(error); | ||
} | ||
|
||
final body = jsonDecode(response.data) as Map<String, Object?>; | ||
if (!body.containsKey('access_token')) { | ||
return handler.reject(error); | ||
} | ||
|
||
final token = body['access_token'] as String; | ||
tokenManager.setAccessToken(token, error.requestOptions.hashCode); | ||
} | ||
|
||
/// Pretend authorization has been resolved and try again | ||
final retried = await dio.fetch( | ||
error.requestOptions | ||
..path = '/mix/s=200' | ||
..headers = { | ||
'Authorization': 'Bearer ${tokenManager.accessToken}', | ||
}, | ||
); | ||
|
||
if (retried.statusCode == null || retried.statusCode! ~/ 100 != 2) { | ||
return handler.reject(error); | ||
} | ||
|
||
return handler.resolve(error.response!); | ||
}, | ||
), | ||
); | ||
printLog(2, createResult.realUri.path); | ||
|
||
await Future.wait([ | ||
dio.post('/mix/s=401'), | ||
dio.post('/mix/s=401'), | ||
dio.post('/mix/s=200'), | ||
]); | ||
|
||
tokenManager.printHistory(); | ||
|
||
dio.close(); | ||
} | ||
|
||
typedef TokenHistory = ({ | ||
String? previous, | ||
String? current, | ||
DateTime updatedAt, | ||
int updatedBy, | ||
}); | ||
|
||
/// Pretend as 'Authentication Server' that generates access token and refresh token | ||
class AuthenticationServer { | ||
static Map<String, String> generate() => <String, String>{ | ||
'access_token': _generateUuid(), | ||
'refresh_token': _generateUuid(), | ||
}; | ||
|
||
static String _generateUuid() { | ||
final random = Random.secure(); | ||
final bytes = List<int>.generate(8, (_) => random.nextInt(256)); | ||
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); | ||
} | ||
} | ||
|
||
class TokenManager { | ||
static String? _accessToken; | ||
|
||
static final List<TokenHistory> _history = <TokenHistory>[]; | ||
|
||
String? get accessToken => _accessToken; | ||
|
||
void printHistory() { | ||
print('=== Token History ==='); | ||
for (int i = 0; i < _history.length; i++) { | ||
final entry = _history[i]; | ||
print(''' | ||
[$i]\tupdated token: ${entry.previous} → ${entry.current} | ||
\tupdated at: ${entry.updatedAt.toIso8601String()} | ||
\tupdated by: ${entry.updatedBy} | ||
'''); | ||
} | ||
} | ||
|
||
void setAccessToken(String? token, int instanceId) { | ||
final previous = _accessToken; | ||
_accessToken = token; | ||
_history.add( | ||
( | ||
previous: previous, | ||
current: _accessToken, | ||
updatedAt: DateTime.now(), | ||
updatedBy: instanceId, | ||
), | ||
); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tokenRefreshDio need close
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I added closing lines for
tokenRefreshDio