node.js - 如何从 Flutter 生成 access_token 并将其发送到节点服务器?
问题描述
我有一个写在 Node.JS 上的 OAuth 服务器,它们接受 access_token 作为请求,然后它生成 JWT,这个 JWT 用于从服务器解锁资源。这是我的 Node.JS 代码,其中包含自述文件中的说明。链接:https ://github.com/Rakshak1344/oAuth
- 需要从flutter中生成access_token。
- 将 access_token 发送到节点路由。
解决方案
方法一:
您可以将用户登录到您的应用程序,该应用程序调用您在 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 中生成令牌。这个博客可以帮助你理解和做好你的工作。
谢谢。
推荐阅读
- python - 将 curl 转换为 python:HTTP 415 不支持的媒体类型
- r - 摘要函数返回 Null 而不是 Max、Min 等
- html - 使画布伸展以填满窗口
- html - HTML 元素在 WordPress 中是不可见的
- java - 在 FlinkRunner 上使用 Beam 的 KafkaIO 时如何修复 NotSeraliazableException
- python - keras v1.2.2 与 keras v2+ 的奇怪行为(准确性差异巨大)
- python - 无法在 Windows 上使用 pip 安装 pytorch
- ember.js - 如何从测试组件触发 Ember 组件中的函数?
- c# - 如何在 Func 委托列表上使用 LINQ where 子句
- android - 如何测试需要授权的屏幕?Espresso + MockWebServer