Flutter:在http调用过程中令牌过期时如何刷新令牌?

5lwkijsr  于 2023-03-13  发布在  Flutter
关注(0)|答案(3)|浏览(216)

我是flutter的新手,我正在使用http包进行网络调用。如果请求的响应代码为200,我想刷新令牌并再次调用请求。我如何使用http包实现这一点?我听说过dio包,但对我来说很复杂。

User getUser(){

   final response = http.post(Uri.https(BASE_URL, '/api/user'), 
    headers: {'Authorization: Bearer $token'});

    if(response.statusCode == 200){
       return User.fromJson(jsonDecode(response.body)['user']);
    }
    else if(response.statusCode == 401){
      //refresh token and call getUser again     
    }

}
hmae6n7t

hmae6n7t1#

可以按如下方式使用刷新标记:

User getUser(){

   final response = http.post(Uri.https(BASE_URL, '/api/user'), 
    headers: {'Authorization: Bearer $token'});

    if(response.statusCode == 200){
       return User.fromJson(jsonDecode(response.body)['user']);
    }
    else if(response.statusCode == 401){
      //refresh token and call getUser again
      final response = http.post(Uri.https(BASE_URL, '/api/[YourAuthorizationEndpoint]'), 
    headers: {'grant_type': 'refresh_token', 'refresh_token': '$refresh_token'});
      token = jsonDecode(response.body)['token'];
      refresh_token = jsonDecode(response.body)['refresh_token'];
      return getUser();
    }

}
jexiocij

jexiocij2#

您可以使用dart的http/retry包:

import 'package:http/http.dart' as http;
import 'package:http_retry/http_retry.dart';

final client = RetryClient(
   http.Client(), 
   retries: 1,
   when: (response) {
    return response.statusCode == 401;
   },
   onRetry: (req, res, retryCount) {
     if (retryCount == 0 && res?.statusCode == 401) {
        // refresh token
     }  
   },
);

try {
  final response = await client.get('http://www.example.com');
} finally {
  client.close();
}
bvhaajcl

bvhaajcl3#

调用API以在到期后刷新令牌
您可以使用此[软件包][1]
[1]:https://pub.dev/packages/jwt_decoder检查令牌是否过期
还可以获取自创建内标识以来的时间和过期日期

相关问题