首页 > 解决方案 > 如何从 Flutter 生成 access_token 并将其发送到节点服务器?

问题描述

我有一个写在 Node.JS 上的 OAuth 服务器,它们接受 access_token 作为请求,然后它生成 JWT,这个 JWT 用于从服务器解锁资源。这是我的 Node.JS 代码,其中包含自述文件中的说明。链接:https ://github.com/Rakshak1344/oAuth

  1. 需要从flutter中生成access_token。
  2. 将 access_token 发送到节点路由。

标签: node.jsflutteroauth

解决方案


方法一:

您可以将用户登录到您的应用程序,该应用程序调用您在 NodeJS 服务器上编写的登录 API。在该 API 中,您可以生成令牌并在该登录服务的响应中返回该令牌。

在 Flutter 中,您可以将返回的令牌保存在 Shared Preferences 中,然后在每个服务中使用该保存的令牌,直到该令牌过期或用户注销。

示例代码:

Future<String> Login(email, password) async {

    final url = "API_URL";
    var result = null;
    final prefs = await SharedPreferences.getInstance();
    var request = { "email": email, "password": password };
    var body = json.encode(request);
    var headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };

    await http.post(url, body: body, headers: headers).then((response) {
      print("Response body: ${response.body}");
      if(response.statusCode == 200){
        var json = jsonDecode(response.body);
        prefs.setString('token', json['token']);
        result = response.body;
      }
      else{
        var json = jsonDecode(response.body);
        print(json['error']['message']);
        result = json['error']['message'];
      }
    });
    return result;
}

方法二:

你可以使用这个包在 Flutter 中生成令牌。这个博客可以帮助你理解和做好你的工作。

谢谢。


推荐阅读