【问题标题】:Flutter http authenticator service to refresh oauth2 tokenFlutter http身份验证器服务刷新oauth2令牌
【发布时间】:2020-01-16 09:03:05
【问题描述】:

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

【问题讨论】:

    标签: http authentication flutter oauth-2.0 refresh-token


    【解决方案1】:

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

    【讨论】:

    • 是的,我期待在颤振中出现相同的行为。我认为 dio 包做同样的功能
    【解决方案2】:

    使用 dio 拦截器

    下面是我的拦截器的一个 sn-p

     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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2017-11-08
      • 2015-01-08
      • 2015-11-02
      • 2016-07-17
      • 2020-07-07
      • 2014-12-01
      • 2015-10-01
      相关资源
      最近更新 更多