Flutter 如何處理401 未授權的 Dio 攔截器

會煮咖啡的貓發表於2021-07-09

正文

在本文中,我將解釋如何使用 flutter dio (4.0.0)進行網路呼叫,以及如何在您的 flutter 應用程式中使用重新整理令牌和訪問令牌來處理授權時處理 401。

在閱讀這篇文章之前,我希望你們對顫抖移動應用程式開發有一個基本的瞭解。

Basic Authentication flow with refresh and access tokens

正如您在上面的圖中所看到的,很明顯,在身份驗證流中使用重新整理和訪問令牌時的流程是什麼。登入後,您將獲得兩個稱為重新整理和訪問的標記。此訪問令牌快速過期(重新整理令牌也過期,但是它將比訪問令牌花費更多的時間)。當您使用過期的訪問令牌發出請求時,響應中會出現狀態碼 401(未經授權)。在這種情況下,您必須從伺服器請求一個新的令牌,並使用有效的訪問令牌再次發出上一個請求。如果重新整理令牌也已過期,您必須指示使用者登入頁面並強制再次登入。

Dio class

class DioUtil {
  static Dio _instance;//method for getting dio instance  Dio getInstance() {
    if (_instance == null) {
      _instance = createDioInstance();
    }
    return _instance;
  }

   Dio createDioInstance() {
    var dio = Dio();// adding interceptor    dio.interceptors.clear();
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      return handler.next(options);
    }, onResponse: (response, handler) {
      if (response != null) {
        return handler.next(response);
      } else {
        return null;
      }
    }, onError: (DioError e, handler) async {

        if (e.response != null) {
          if (e.response.statusCode == 401) {//catch the 401 here
            dio.interceptors.requestLock.lock();
            dio.interceptors.responseLock.lock();
            RequestOptions requestOptions = e.requestOptions;

            await refreshToken();
            Repository repository = Repository();
            var accessToken = await repository.readData("accessToken");
            final opts = new Options(method: requestOptions.method);
            dio.options.headers["Authorization"] = "Bearer " + accessToken;
            dio.options.headers["Accept"] = "*/*";
            dio.interceptors.requestLock.unlock();
            dio.interceptors.responseLock.unlock();
            final response = await dio.request(requestOptions.path,
                options: opts,
                cancelToken: requestOptions.cancelToken,
                onReceiveProgress: requestOptions.onReceiveProgress,
                data: requestOptions.data,
                queryParameters: requestOptions.queryParameters);
            if (response != null) {
              handler.resolve(response);
            } else {
              return null;
            }
          } else {
            handler.next(e);
          }
        }

    }));
    return dio;
  }

  static refreshToken() async {
    Response response;
    Repository repository = Repository();
    var dio = Dio();
    final Uri apiUrl = Uri.parse(BASE_PATH + "auth/reIssueAccessToken");
    var refreshToken = await repository.readData("refreshToken");
    dio.options.headers["Authorization"] = "Bearer " + refreshToken;
    try {
      response = await dio.postUri(apiUrl);
      if (response.statusCode == 200) {
        LoginResponse loginResponse =
            LoginResponse.fromJson(jsonDecode(response.toString()));
        repository.addValue('accessToken', loginResponse.data.accessToken);
        repository.addValue('refreshToken', loginResponse.data.refreshToken);
      } else {
        print(response.toString()); //TODO: logout
      }
    } catch (e) {
      print(e.toString()); //TODO: logout
    }
  }
}
複製程式碼

以上是完整的課程,我將解釋其中最重要的部分。

主要是,正如您在 createDioInstance 方法中看到的,您必須新增一個攔截器來捕獲 401。當 401 發生在 error: (DioError e,handler) async {}被呼叫時。所以你的內心

  1. Check the error code(401), 檢查錯誤程式碼(401) ,
  2. Get new access token 獲取新的訪問令牌
await refreshToken();
複製程式碼

上面的程式碼將呼叫 refreshToken 方法並在儲存庫中儲存新的重新整理和訪問令牌。(對於儲存庫,您可以使用 secure storage or shared preferences)

  1. 複製前一個請求並設定新的訪問令牌
RequestOptions requestOptions = e.requestOptions;
Repository repository = Repository();
var accessToken = await repository.readData("accessToken");
final opts = new Options(method: requestOptions.method);
dio.options.headers["Authorization"] = "Bearer " + accessToken;
dio.options.headers["Accept"] = "*/*";
複製程式碼
  1. Make the previous call again
final response = await dio.request(requestOptions.path,
    options: opts,
    cancelToken: requestOptions.cancelToken,
    onReceiveProgress: requestOptions.onReceiveProgress,
    data: requestOptions.data,
    queryParameters: requestOptions.queryParameters);
複製程式碼

一旦收到回覆,就 call

handler.resolve(response);
複製程式碼

然後響應將被髮送到您呼叫 api 的位置,如下所示。

var dio = DioUtil().getInstance();
final String apiUrl = (BASE_PATH + "payments/addNewPayment/");
var accessToken = await repository.readData("accessToken");
dio.options.headers["Authorization"] = "Bearer " + accessToken;
dio.options.headers["Accept"] = "*/*";//response will be assigned to response variable
response = await dio.post(apiUrl, data: event.paymentRequest.toJson());
複製程式碼

Thats all. happy coding :)


© 貓哥

ducafecat.tech/

github.com/ducafecat

往期

開源

GetX Quick Start

github.com/ducafecat/g…

新聞客戶端

github.com/ducafecat/f…

strapi 手冊譯文

getstrapi.cn

微信討論群 ducafecat

系列集合

譯文

ducafecat.tech/categories/…

開源專案

ducafecat.tech/categories/…

Dart 程式語言基礎

space.bilibili.com/404904528/c…

Flutter 零基礎入門

space.bilibili.com/404904528/c…

Flutter 實戰從零開始 新聞客戶端

space.bilibili.com/404904528/c…

Flutter 元件開發

space.bilibili.com/404904528/c…

Flutter Bloc

space.bilibili.com/404904528/c…

Flutter Getx4

space.bilibili.com/404904528/c…

Docker Yapi

space.bilibili.com/404904528/c…

相關文章