簡體   English   中英

郵遞員上的授權類型承載令牌,並從 API 請求數據,這需要帶有顫振的令牌承載

[英]authorization type bearer token on postman and request data from the API which requires a token bearer with flutter

我試圖從我的 API 請求數據並獲取數據,它需要一個可以通過登錄獲取的不記名令牌。 作為前端,我創建了一個函數來保存和從 UI 請求到 API。 我正在為 UI 使用顫振框架。

我設法創建了一個函數來存儲登錄時生成的不記名令牌,它使用戶保持登錄狀態。它通過將不記名令牌保存在 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類:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM