此答案基于#edit1。既然您提到您已经知道如何在服务器端设置令牌,那么您已经完成了一半。这是我所做的一些假设,您已经了解 js/php 并使用 JSON 输出,数据库已经有一个列和表来跟踪会话和 user_id。
既然您知道 Cookie 是如何构建的,这应该相对容易,因为我围绕类似的架构构建它。我们必须使用应用程序提供访问权限的本地内存。颤振中有两个包可以让你这样做,你可以使用任何一个:
主要区别在于,如果您想存储“令牌”或您想要安全的数据,您显然会使用 flutter_secure_storage。我将使用它作为代码示例。是的,即使应用程序关闭,数据也会保存。
设置令牌(颤振):
- 设置用户类
在使用 firebase 时,我们通常认为 flutter_auth 附带的用户类是理所当然的,但这基本上是我们必须构建的。一个包含你想要存储的所有数据的用户类,然后是一个名为 authenticate 的函数。
class AppUser{
final _storage = new FlutterSecureStorage();
//below class is mentioned in the next part
AuthApi api = new AuthApi();
//constructor
AppUser(){
//ur data;
};
Future<bool> authenticate(email, password) async {
//this is the api mentioned in next part
http.Response res = await api.login(email, password);
Map<String, dynamic> jsonRes = jsonDecode(res.body);
if (jsonRes["error"]) {
return false;
}
_setToken(jsonRes["token"]);
_setUID(jsonRes["user-id"].toString());
_setAuthState(true);
return true;
}
Future<void> _setToken(String val) async {
//how to write to safe_storage
await _storage.write(key: 'token', value: val);
}
Future<void> _setUID(String val) async {
await _storage.write(key: 'user_id', value: val);
}
//you can stream this or use it in a wrapper to help navigate
Future<bool> isAuthenticated() async {
bool authState = await _getAuthState();
return authState;
}
Future<void> _getAuthState() async {
//how to read from safe_storage u can use the same to read token later just replace 'state' with 'token'
String myState = (await _storage.read(key: 'state')).toString();
//returns boolean true or false
return myState.toLowerCase() == 'true';
}
Future<void> _setAuthState(bool liveAuthState) async {
await _storage.write(key: 'state', value: liveAuthState.toString());
}
}
并假设您要在按下按钮时进行身份验证,所以它看起来像
onPressed(){
AuthUser user = new AuthUser();
if(user.authenticate(email, password)){
//if logged in. Prolly call Navigator.
}else{
//handle error
}
}
- 设置 api 调用
好吧,这是调用 Node express API,json 输出看起来像
//if successful
{"status":200, "error": false, "token": "sha256token", "user-id": "uid"}
我们需要创建一个类,该类将为我们提供进行此调用的输出,因此是 AuthApi 类
class AuthApi {
//this is the login api and it returns the above JSON
Future<http.Response> login(String email, String password){
return http.post(
Uri.parse(ip + '/api/auth/login'),
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, String>{
"email": email,
"password": password,
}),
);
}
}
感谢您澄清您需要什么,它有助于更好地回答。