Flutter Clean架构中授权令牌的全局访问

问题描述 投票:0回答:1

我想知道是否可以以某种方式使授权令牌在我的应用程序代码中的任何地方都可访问,同时尊重干净架构的规则,知道它可能会发生变化,例如,如果用户断开连接,并且身份验证由特定的“身份验证”管理“ 特征。 也许我必须在每个需要它的数据源方法的参数中输入它?

@override
  Future<(List<AlimentModel>, int)> getAllAliments() async {
    final http.Response response = await client.get(
      Uri.http(
        APIBaseURL,
        '$routeName/all',
      ),
      headers: generateHeaders(
        contentType: null,
        authorization: token, // authorization header needed here
      ),
    );
    if (response.statusCode == 200) {
      final Map<String, dynamic> json = jsonDecode(response.body);
      final List<Map<String, dynamic>> alimentsJson = json['aliments'];
      final List<AlimentModel> aliments =
          AlimentModel.fromJsonToList(alimentsJson);
      final int alimentsLastUpdate = json['alimentsLastUpdate'];
      return (aliments, alimentsLastUpdate);
    } else {
      throw ServerException(
        statusCode: response.statusCode,
        error: jsonDecode(response.body)['error'],
      );
    }
  }

我尝试在 get_it 中创建 SessionToken 单例,但它似乎不是很干净。

flutter dart bloc clean-architecture
1个回答
0
投票

这是我向您建议的策略,使代币可以在全球范围内访问,同时尊重干净的架构。 无法访问您的代码,但这是我建议您实施的策略,然后由您来调整它以适应您的项目。

  • 在域部分

您创建了一个TokenRepository

abstract class TokenRepository {
  String? getToken();
  void setToken(String? token);
}
  • 基础设施层

您创建实现 TokenRepository 接口的 TokenRepositoryImpl

class TokenRepositoryImpl implements TokenRepository {
  String? _token;

  @override
  String? getToken() => _token;

  @override
  void setToken(String? token) {
    _token = token;
    // you can implement secure token storage here
  }
}

在实现 getAllAliments() 方法的数据源中,使用 TokenRepository 来获取令牌

class YourDataSource {
  final TokenRepository tokenRepository;
  YourDataSource({required this.client, required this.tokenRepository});

  @override
  Future<(List<AlimentModel>, int)> getAllAliments() async {
    final http.Response response = await client.get(
      Uri.http(
        APIBaseURL,
        '$routeName/all',
      ),
      headers: generateHeaders(
        contentType: null,
        authorization:
            tokenRepository.getToken(), // use like that the token here the tokeauthorization header needed here
      ),
    );
    if (response.statusCode == 200) {
      final Map<String, dynamic> json = jsonDecode(response.body);
      final List<Map<String, dynamic>> alimentsJson = json['aliments'];
      final List<AlimentModel> aliments =
          AlimentModel.fromJsonToList(alimentsJson);
      final int alimentsLastUpdate = json['alimentsLastUpdate'];
      return (aliments, alimentsLastUpdate);
    } else {
      throw ServerException(
        statusCode: response.statusCode,
        error: jsonDecode(response.body)['error'],
      );
    }
  }
}

在身份验证服务中,您检索您的令牌

class AuthService {
  final TokenRepository tokenRepository;
  final AuthenticationRemoteDataSource authDataSource;

  AuthService({required this.tokenRepository, required this.authDataSource});

  Future<void> login(String username, String password) async {
    final token = await authDataSource.authenticate(username, password);
    tokenRepository.setToken(token);
  }

  void logout() {
    tokenRepository.setToken(null);
  }
}

并完成配置依赖注入

getIt.registerLazySingleton<TokenRepository>(() => TokenRepositoryImpl());
getIt.registerFactory<YourDataSource>(() =>  YourDataSource(client: http.Client(), tokenRepository: getIt<TokenRepository>()));
getIt.registerFactory<AuthService>(() => AuthService(tokenRepository: getIt<TokenRepository>(), authDataSource: AuthenticationRemoteDataSource()));

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.