简体   繁体   English

Flutter http 身份验证器服务以刷新 oauth2 令牌

[英]Flutter http authenticator service to refresh oauth2 token

I am working on oauth2 authentication in a flutter app.我正在 Flutter 应用程序中进行 oauth2 身份验证。 I am thinking of refreshing the token when 401 authentication error happens in any of my API's.我正在考虑在我的任何 API 中发生 401 身份验证错误时刷新令牌。 So how to add an authenticator service to all the http requests in flutter.那么如何给flutter中的所有http请求添加一个authenticator服务呢? In android we have okhttp authenticator to detect the authentication error during any API call and can refresh the token and proceed the previous API call.在android中,我们有okhttp身份验证器来检测任何API调用期间的身份验证错误,并且可以刷新令牌并继续之前的API调用。 In flutter how to implement this?在颤振中如何实现这一点? I dont think it is a good practice to handle 401 error in all the API's.我不认为在所有 API 中处理 401 错误是一个好习惯。

Use dio interceptor使用dio拦截器

Below is a snippet from my interceptor下面是我的拦截器的片段

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

I tend to use the pattern of parameterizing all API calls on the client side, as in this code snippet .我倾向于在客户端使用参数化所有 API 调用的模式, 如此代码片段所示 This approach should work in any technology, though in some techs you may have options to implement it via some kind of interceptor class.这种方法应该适用于任何技术,但在某些技术中,您可能可以选择通过某种拦截器类来实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM