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

image

老鐵記得 轉發 ,貓哥會呈現更多 Flutter 好文~~~~

微信群 ducafecat

b 站 https://space.bilibili.com/404904528

原文

https://medium.com/@wmnkrishanmadushanka/how-to-handle-401-unauthorised-with-dio-interceptor-flutter-60398a914406

參考

正文

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

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

Basic Authentication flow with refresh and access tokens

image

正如您在上面的圖中所看到的,很明顯,在身份驗證流中使用刷新和訪問令牌時的流程是什么。登錄后,您將獲得兩個稱為刷新和訪問的標記。此訪問令牌快速過期(刷新令牌也過期,但是它將比訪問令牌花費更多的時間)。當您使用過期的訪問令牌發出請求時,響應中會出現狀態碼 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 :)


? 貓哥

https://ducafecat.tech/

https://github.com/ducafecat

往期

開源

GetX Quick Start

https://github.com/ducafecat/getx_quick_start

新聞客戶端

https://github.com/ducafecat/flutter_learn_news

strapi 手冊譯文

https://getstrapi.cn

微信討論群 ducafecat

系列集合

譯文

https://ducafecat.tech/categories/%E8%AF%91%E6%96%87/

開源項目

https://ducafecat.tech/categories/%E5%BC%80%E6%BA%90/

Dart 編程語言基礎

https://space.bilibili.com/404904528/channel/detail?cid=111585

Flutter 零基礎入門

https://space.bilibili.com/404904528/channel/detail?cid=123470

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

https://space.bilibili.com/404904528/channel/detail?cid=106755

Flutter 組件開發

https://space.bilibili.com/404904528/channel/detail?cid=144262

Flutter Bloc

https://space.bilibili.com/404904528/channel/detail?cid=177519

Flutter Getx4

https://space.bilibili.com/404904528/channel/detail?cid=177514

Docker Yapi

https://space.bilibili.com/404904528/channel/detail?cid=130578

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容