我是新来的。基本上,我在Web应用程序中使用代码Igniter框架。我为我的Web应用程序创建了REST API,在用户使用API登录后,所有方法都会检查session_id是否存在,然后继续进行,如果不存在,则给出
{ ['status'] = false, ['message'] = 'unauthorized access' }
Run Code Online (Sandbox Code Playgroud)
我正在使用flutter创建应用程序,当我使用flutter的http方法时,它将更改每个请求的会话。我的意思是,它不维护会话。我认为它每次都会破坏并创建新的连接。这是我用于API调用get和post请求的thr类方法。
class ApiCall {
static Map data;
static List keys;
static Future<Map> getData(url) async {
http.Response response = await http.get(url);
Map body = JSON.decode(response.body);
data = body;
return body;
}
static Future postData(url, data) async {
Map result;
http.Response response = await http.post(url, body: data).then((response) {
result = JSON.decode(response.body);
}).catchError((error) => print(error.toString()));
data = result;
keys = result.keys.toList();
return result;
}
Run Code Online (Sandbox Code Playgroud)
我想发出API请求,然后存储session_id,是否可以在服务器上维护会话,以便我可以自行管理Web应用程序上的身份验证?
HTTP是一种无状态协议,因此服务器需要某种方式来识别客户端向服务器发出的第二,第三和后续请求中的客户端。在您的情况下,您可以使用第一个请求进行身份验证,因此您希望服务器在后续请求中记住您,以便服务器知道您已通过身份验证。常用的方法是使用cookie。
点火器发送带有会话ID的cookie。您需要从每个响应中收集此信息,然后在下一个请求中将其发送回去。(服务器有时会更改会话ID(以减少我们不需要考虑的诸如clickjacking之类的事情),因此您需要继续从每个响应中提取cookie。)
Cookie以称为的HTTP响应标头的形式到达set-cookie(可能有多个,尽管希望不是为了简单)。要发回Cookie,请在后续请求中添加HTTP请求标头,称为cookie,复制从set-cookie标头提取的某些信息。
希望Igniter仅发送一个set-cookie标头,但出于调试目的,您可能会发现使用可以打印所有标头response.headers.forEach((a, b) => print('$a: $b'));。您应该找到Set-Cookie: somename=abcdef; optional stuff。我们需要提取字符串,但不包括;,即somename=abcdef
在下一个及后续请求上{'Cookie': 'somename=abcdef'},通过将post命令更改为:将请求标头添加到的下一个请求中:
http.post(url, body: data, headers:{'Cookie': cookie})
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我认为您在上面的代码中awaits与和不匹配then。通常,如果类应该是顶级函数,则不希望使用类中的静态函数。相反,您可以创建一个支持cookie的类,例如:
class Session {
Map<String, String> headers = {};
Future<Map> get(String url) async {
http.Response response = await http.get(url, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
Future<Map> post(String url, dynamic data) async {
http.Response response = await http.post(url, body: data, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
void updateCookie(http.Response response) {
String rawCookie = response.headers['set-cookie'];
if (rawCookie != null) {
int index = rawCookie.indexOf(';');
headers['cookie'] =
(index == -1) ? rawCookie : rawCookie.substring(0, index);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3157 次 |
| 最近记录: |