用于刷新 oauth2 令牌的 Flutter http 身份验证器服务

Flutter http authenticator service to refresh oauth2 token

我正在 flutter 应用程序中进行 oauth2 身份验证。当我的 API 中的任何一个发生 401 身份验证错误时,我正在考虑刷新令牌。那么如何在flutter中为所有的http请求添加一个authenticator服务。在 android 中,我们有 okhttp 身份验证器来检测任何 API 调用期间的身份验证错误,并且可以刷新令牌并继续之前的 API 调用。在颤动中如何实现这个?我认为在所有 API 中处理 401 错误不是一个好习惯。

我倾向于在客户端使用参数化所有 API 调用的模式,如 this code snippet 中那样。这种方法应该适用于任何技术,尽管在某些技术中你可以选择通过某种拦截器来实现它 class.

使用dio拦截器

下面是我的拦截器的一个片段

 dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {

/* Write your request logic setting your Authorization header from prefs*/

      String token = await prefs.accessToken;
      if (token != null) {
        options.headers["Authorization"] = "Bearer " + token;
      return options; //continue
    }, onResponse: (Response response) async {
// Write your response logic

      return response; // continue
    }, onError: (DioError dioError) async {

      // Refresh Token
      if (dioError.response?.statusCode == 401) {
        Response response;
        var data = <String, dynamic>{
          "grant_type": "refresh_token",
          "refresh_token": await prefs.refreshToken,
          'email': await prefs.userEmail
        };
        response = await dio
            .post("api/url/for/refresh/token", data: data);
        if (response.statusCode == 200) {
          var newRefreshToken = response.data["data"]["refresh_token"]; // get new refresh token from response
          var newAccessToken = response.data["data"]["access_token"]; // get new access token from response
          prefs.refreshToken = newRefreshToken;
          prefs.accessToken = newAccessToken; // to be used in the request section of the interceptor
          return dio.request(dioError.request.baseUrl + dioError.request.path,
              options: dioError.request);
        }
      }
      return dioError;
    }));
    return dio;
  }
}