【问题标题】:authorization type bearer token on postman and request data from the API which requires a token bearer with flutter邮递员上的授权类型不记名令牌和来自 API 的请求数据,这需要带有颤振的令牌不记名
【发布时间】:2021-02-08 09:13:24
【问题描述】:

我试图从我的 API 请求数据并获取数据,它需要一个可以通过登录获得的不记名令牌。作为前端,我创建了一个函数来保存和请求从 UI 到 API。我正在为 UI 使用 Flutter 框架。

我设法创建了一个函数来存储登录时生成的不记名令牌,以保持用户登录状态。它通过将不记名令牌保存在 sharedpref 中来工作。

login() async {
final response = await http.post(
  "https://api.batulimee.com//v1_ship/login_app",
  body: {"email": email, "password": password},
);  
final data = jsonDecode(response.body);
String status = data['status'];
String pesan = data['message'];
String apikey = data['data']['apikey'];
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('apikey', apikey);

if (status == "success") {
  Navigator.of(context).pushReplacement(PageRouteBuilder(
      pageBuilder: (_, __, ___) => new bottomNavBar(),
      transitionDuration: Duration(milliseconds: 600),
      transitionsBuilder:
          (_, Animation<double> animation, __, Widget child) {
        return Opacity(
          opacity: animation.value,
          child: child,
        );
      }));
  print(pesan);
  print(apikey);
} else {
  print(pesan);
}
}

这是回复。

{
"status": "success",
"data": {
    "apikey": "UUFmb0w3WlI4Q01qOWRTamgxOFVZRjhIeWhFMkN3T205R20xZXNpYw==",
    "id_user": 50,
    "id_role": "8",
    "name_role": "Ship Owner",
    "email": "me@gmail.com",
    "phone": "0210201",
    "saldo": "0",
    "photo": "https://cdn.batulimee.com/foto_user/avatar.png"
},
"message": "login successfully "
}

现在我想创建一个可以获取用户配置文件数据的函数,并且从哪里获取这些数据需要我从登录中获得的不记名令牌。我需要这个,以便用户可以在用户个人资料中编辑他们的姓名、密码或其他数据并保存。

我的后端创建了 API get my_profile。我之前解释过,要获得它需要一个与我们之前从登录获得的令牌持有者相同的令牌持有者。现在我的工作是使用 Flutter 中的函数获取 get my_profile 数据。

这是来自 API get my_profile 的响应。

{
"status": "success",
"data": {
"id_user": 49,
"id_role": "8",
"name_role": "Ship Owner",
"first_name": "a",
"last_name": "f",
"email": "afriansyahm86@gmail.com",
"phone": "082258785595",
"saldo": "0",
"company_name": "aa",
"company_address": "jl kav pgri",
"photo": "https://batulimee.com/foto_user/avatar.png"
},
"message": "get profile detail successfully "
}

如何将不记名令牌存储到授权中以便我可以获取 my_profile 数据?请帮帮我.... :(

【问题讨论】:

    标签: api flutter dart postman bearer-token


    【解决方案1】:

    创建一个 api 类:

    import 'package:http/io_client.dart';
    class Api {
    
      String _token;
    
     final Client http =IOClient(HttpClient()
        ..badCertificateCallback = _certificateCheck
        ..connectionTimeout = const Duration(seconds: kConnectionTimeoutSeconds));
    static bool _certificateCheck(X509Certificate cert, String host, int port) =>
      host.endsWith('EXAMPLE.com'); // Enter your url for api here
      String GetToken() {
        return _token;
      }
    Future<bool> setToken(String token) async {
        _token = token;
        return Future.value(true);
      }
    Map<String, String> get headers => {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": "Bearer $_token",
          };
    

    }

    在您的登录中使用 setToken:

    等待_api.setToken(apikey);

    您的个人资料或 api 类中的任何请求的下一个:

    Future<ProfileResponse> getProfile() async {
        var url = "$urlPrefix/api/v1/profile";
    
        var response = await http.get(url, headers: headers);
    
        if (response.statusCode != 200) {
          print(
              "$response");
          var parsed = json.decode(response.body);
          var message = parsed["message"];
          if (message != null) {
            throw message;
          }
    
          throw Exception(
              "Request to $url failed with status ${response.statusCode}: ${response.body}");
        }
        // return the response you want 
        return json.decode(response.body);
      }
    

    【讨论】:

    • 最终客户端 http = StatsInterceptor(IOClient(HttpClient() ..badCertificateCallback = _certificateCheck ..connectionTimeout = const Duration(seconds: kConnectionTimeoutSeconds))); String GetToken() { return _token; }
    • 什么是 StatsInterceptor?
    • 您可以删除 stateIntercepror,我的代码中有它,如果失败则重试。但是您可以简单地使用:Client http = http.Client();
    • 啊,我明白了,谢谢。对不起,你能解释一下 setToken: await _api.setToken(apikey); 吗?
    • 在下面的登录类中添加该行:print(apikey); 你必须在此处导入 api 类并将其作为 final 添加到你的登录类中,然后你就可以使用它了
    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2018-09-21
    • 2021-08-02
    • 2020-11-24
    • 2020-01-24
    • 1970-01-01
    • 2018-09-22
    • 2021-10-05
    相关资源
    最近更新 更多