-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathqueued_interceptor_crsftoken.dart
172 lines (144 loc) · 4.87 KB
/
queued_interceptor_crsftoken.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import 'dart:convert';
import 'dart:math';
import 'package:dio/dio.dart';
void main() async {
final tokenManager = TokenManager();
final dio = Dio(
BaseOptions(
baseUrl: 'https://httpbun.com',
),
);
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',
// request a 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 the '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!);
}
// To prevent repeated requests to the 'Authentication Server'
// to update our 'access_token' with parallel requests,
// we need to 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(
'/mix/s=201/b64=${base64.encode(
jsonEncode(AuthenticationServer.generate()).codeUnits,
)}',
);
tokenRefreshDio.close();
// Treat codes other than 2XX as rejected.
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);
}
/// The authorization has been resolved so and try again with the request.
final retried = await dio.fetch(
error.requestOptions
..path = '/mix/s=200'
..headers = {
'Authorization': 'Bearer ${tokenManager.accessToken}',
},
);
// Treat codes other than 2XX as rejected.
if (retried.statusCode == null || retried.statusCode! ~/ 100 != 2) {
return handler.reject(error);
}
return handler.resolve(error.response!);
},
),
);
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,
),
);
}
}