如何在改造Flutter中添加承载令牌授权

ibrsph3r  于 2023-05-29  发布在  Flutter
关注(0)|答案(2)|浏览(156)

如何在Retrofit Flutter中添加承载令牌授权。
这里是改装服务

@RestApi(baseUrl: "https://***.****.xyz/api/")
abstract class ApiService{

  factory ApiService(Dio dio) => _ApiService(dio);

  @POST("auth/login")
  Future<AuthModel> login(@Body() Map<String,dynamic> map);

  @POST("auth/singup")
  Future<AuthModel> singup(@Body() Map<String,dynamic> map);

  @GET('{id}')
  Future<UserModel> getUser( @Path() String id);

}

然后创建Dio并添加到GetIt并插入ApiService。

var getIt = GetIt.I;
void locator(){

  Dio dio = Dio();
  

  getIt.registerLazySingleton(() => dio);

   ApiService apiService = ApiService(getIt.call());
  getIt.registerLazySingleton(() => apiService);

  Repository repository = Repository(getIt.call());
  getIt.registerLazySingleton(() => repository);

  LoginCubit loginCubit = LoginCubit(getIt.call());
  getIt.registerLazySingleton(() => loginCubit);
 
  GetProfileCubit getProfileCubit = GetProfileCubit(getIt.call());
  getIt.registerLazySingleton(() => getProfileCubit);

}

和创建存储库

class Repository{
  final ApiService _apiService;
  Repository(this._apiService);

  Future<AuthModel> logIn(Map<String,dynamic> map) => _apiService.login(map);
  Future<AuthModel> singUp(Map<String,dynamic> map) => _apiService.singup(map);
  Future<UserModel> getUser(String id) => _apiService.getUser(id);

}

请回答我的问题,先生。对不起我的英语。

2uluyalo

2uluyalo1#

这不是最佳方法,但应该可以正常工作。
按如下方式更改ApiService类:

@RestApi(baseUrl: "https://***.****.xyz/api/")
abstract class ApiService{

   .... same code ....

  @GET('{id}')
  Future<UserModel> getUser( 
     @Header('Authorization') String token,
     @Path() String id
       );

 .... same code ....
}

同时更改Repository类:

class Repository{
  .... same code ...
  //// Pass token as a parameter
  ///// Add Bearer before your token
 
  Future<UserModel> getUser(String token, String id) => 
      _apiService.getUser('Bearer $token',id);

}

快乐编码TT

5gfr0r5j

5gfr0r5j2#

Retrofit使用Dio,因此您可以实现Dio拦截器。
下面是一个如何创建拦截器的示例。

class TokenInterceptor extends Interceptor {

  @override
  Future onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    // Here you can put the token, either from preference, sqlite, etc.
    // Here is an example with Preferences
    final someToken? = prefs.getString('token');
    // After you choose your token, you assign it to the request.
    options.headers['Authorization'] = 'Bearer ${someToken}';
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // Do something with response data
    super.onResponse(response, handler);
  }

  @override
  Future onError(
    DioError err,
    ErrorInterceptorHandler handler,
  ) async {
    // If the error is 401 Unauthorized, log out the user
    if (err.response?.statusCode == 401) {
      _repository.logOut();
      _appDatabase.userDao.deleteAllUsers();
    }
    super.onError(err, handler);
  }
}

那么你必须将拦截器添加到Dio中

var getIt = GetIt.I;
void locator(){

  Dio dio = Dio();
  dio.interceptors.add(TokenInterceptor()); // Add this code

  getIt.registerLazySingleton(() => dio);

   ApiService apiService = ApiService(getIt.call());
  getIt.registerLazySingleton(() => apiService);

  Repository repository = Repository(getIt.call());
  getIt.registerLazySingleton(() => repository);

  LoginCubit loginCubit = LoginCubit(getIt.call());
  getIt.registerLazySingleton(() => loginCubit);
 
  GetProfileCubit getProfileCubit = GetProfileCubit(getIt.call());
  getIt.registerLazySingleton(() => getProfileCubit);

}

Linkedin有一个很好的职位与更多的配置,可能是有趣的.

相关问题