修复用户端令牌失效后的登录恢复
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// 功能描述:封装用户端 HTTP 请求,并将服务端错误转换为安全、可读的中文提示。
|
||||
// 版本:1.1.0
|
||||
// 版本:1.2.0
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
@@ -84,12 +84,21 @@ class ApiException implements Exception {
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 表示鉴权会话已经失效;页面层应等待路由跳转,不再展示普通网络错误。
|
||||
class SessionExpiredException extends ApiException {
|
||||
const SessionExpiredException() : super(401, '登录状态已失效,请重新登录');
|
||||
}
|
||||
|
||||
/// 接收被服务端拒绝的请求令牌,用于安全地失效对应会话。
|
||||
typedef UnauthorizedCallback = void Function(String rejectedToken);
|
||||
|
||||
/// 负责用户端统一 HTTP 请求、鉴权头和响应解析。
|
||||
class ApiClient {
|
||||
ApiClient(
|
||||
this._tokenProvider, {
|
||||
http.Client? client,
|
||||
String? baseUrl,
|
||||
this.onUnauthorized,
|
||||
}) : _client = client ?? http.Client(),
|
||||
baseUrl =
|
||||
baseUrl ??
|
||||
@@ -101,6 +110,7 @@ class ApiClient {
|
||||
final String baseUrl;
|
||||
final String Function() _tokenProvider;
|
||||
final http.Client _client;
|
||||
final UnauthorizedCallback? onUnauthorized;
|
||||
|
||||
Future<Object?> get(String path, {bool authenticated = true}) =>
|
||||
_send('GET', path, authenticated: authenticated);
|
||||
@@ -112,6 +122,13 @@ class ApiClient {
|
||||
final token = _tokenProvider();
|
||||
if (token.isNotEmpty) request.headers['authorization'] = token;
|
||||
final response = await _sendRequest(request);
|
||||
if (response.statusCode == 401 && token.isNotEmpty) {
|
||||
_rejectSession(token);
|
||||
}
|
||||
final responseCode = _jsonResponseCode(response);
|
||||
if (token.isNotEmpty && responseCode != null && _isAuthenticationFailure(responseCode)) {
|
||||
_rejectSession(token);
|
||||
}
|
||||
if (response.statusCode == 404) return null;
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw ApiException(response.statusCode, '头像加载失败');
|
||||
@@ -138,16 +155,21 @@ class ApiClient {
|
||||
}) async {
|
||||
final request = http.Request(method, Uri.parse('$baseUrl$path'));
|
||||
request.headers['accept'] = 'application/json';
|
||||
var requestToken = '';
|
||||
if (authenticated) {
|
||||
final token = _tokenProvider();
|
||||
if (token.isNotEmpty) request.headers['authorization'] = token;
|
||||
requestToken = _tokenProvider();
|
||||
if (requestToken.isNotEmpty) request.headers['authorization'] = requestToken;
|
||||
}
|
||||
if (body != null) {
|
||||
request.headers['content-type'] = 'application/json; charset=UTF-8';
|
||||
request.body = jsonEncode(body);
|
||||
}
|
||||
final response = await _sendRequest(request);
|
||||
return _decode(response);
|
||||
return _decode(
|
||||
response,
|
||||
authenticated: authenticated,
|
||||
requestToken: requestToken,
|
||||
);
|
||||
}
|
||||
|
||||
/// 发送请求并统一处理网络连接异常。
|
||||
@@ -160,7 +182,14 @@ class ApiClient {
|
||||
}
|
||||
|
||||
/// 解析统一响应结构,并按错误码生成中文提示。
|
||||
Object? _decode(http.Response response) {
|
||||
Object? _decode(
|
||||
http.Response response, {
|
||||
required bool authenticated,
|
||||
required String requestToken,
|
||||
}) {
|
||||
if (authenticated && response.statusCode == 401 && requestToken.isNotEmpty) {
|
||||
_rejectSession(requestToken);
|
||||
}
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw ApiException(response.statusCode, '网络请求失败(${response.statusCode})');
|
||||
}
|
||||
@@ -175,6 +204,9 @@ class ApiClient {
|
||||
}
|
||||
final code = (decoded['code'] as num?)?.toInt() ?? 500;
|
||||
if (code != 0) {
|
||||
if (authenticated && requestToken.isNotEmpty && _isAuthenticationFailure(code)) {
|
||||
_rejectSession(requestToken);
|
||||
}
|
||||
throw ApiException(
|
||||
code,
|
||||
localizeApiErrorMessage(code, decoded['message'] as String?),
|
||||
@@ -182,8 +214,37 @@ class ApiClient {
|
||||
}
|
||||
return decoded['details'];
|
||||
}
|
||||
|
||||
/// 通知会话层并抛出专用异常,避免页面把鉴权失败误报为网络问题。
|
||||
Never _rejectSession(String rejectedToken) {
|
||||
onUnauthorized?.call(rejectedToken);
|
||||
throw const SessionExpiredException();
|
||||
}
|
||||
|
||||
/// 尝试从二进制接口返回的 JSON 错误体中提取业务码。
|
||||
int? _jsonResponseCode(http.Response response) {
|
||||
final contentType = response.headers['content-type'] ?? '';
|
||||
int? firstContentByte;
|
||||
for (final byte in response.bodyBytes) {
|
||||
if (byte == 0x20 || byte == 0x09 || byte == 0x0a || byte == 0x0d) continue;
|
||||
firstContentByte = byte;
|
||||
break;
|
||||
}
|
||||
if (!contentType.contains('json') && firstContentByte != 0x7b) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
final decoded = jsonDecode(response.body);
|
||||
return decoded is Map ? (decoded['code'] as num?)?.toInt() : null;
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断服务端稳定错误码是否表示登录会话无效。
|
||||
bool _isAuthenticationFailure(int code) => (code >= 1301 && code <= 1314) || code == 1715;
|
||||
|
||||
Map<String, Object?> jsonMap(Object? value) {
|
||||
if (value is Map<String, Object?>) return value;
|
||||
if (value is Map) return value.map((key, item) => MapEntry(key.toString(), item));
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
// 功能描述:封装用户端登录令牌的安全持久化接口与平台实现。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
class SecureSessionStore {
|
||||
/// 定义登录令牌持久化能力,便于会话逻辑隔离具体存储实现。
|
||||
abstract interface class SessionStore {
|
||||
Future<String?> readToken();
|
||||
|
||||
Future<void> writeToken(String token);
|
||||
|
||||
Future<void> clear();
|
||||
}
|
||||
|
||||
/// 使用平台安全存储保存用户端登录令牌。
|
||||
class SecureSessionStore implements SessionStore {
|
||||
SecureSessionStore({FlutterSecureStorage? storage})
|
||||
: _storage = storage ?? const FlutterSecureStorage();
|
||||
|
||||
static const _tokenKey = 'user_app_access_token';
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
@override
|
||||
Future<String?> readToken() => _storage.read(key: _tokenKey);
|
||||
|
||||
@override
|
||||
Future<void> writeToken(String token) => _storage.write(key: _tokenKey, value: token);
|
||||
|
||||
@override
|
||||
Future<void> clear() => _storage.delete(key: _tokenKey);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user