【问题标题】:How to POST in Flutter with cookie or session?如何使用 cookie 或会话在 Flutter 中发布?
【发布时间】:2019-05-31 03:16:45
【问题描述】:

我正在尝试使用 http 在 Flutter 中发送发布请求。

我想使用 OAuth2 登录到自托管的 WordPress 安装。

在第一次请求时它会成功,我会登录并获取 cookie。但是在第二个请求中,我尝试在标头中设置响应的 cookie 并获取令牌,但响应为 302,我认为 cookie 或会话没有在标头中设置或类似的东西。

Swift 工作版本:

https://github.com/wlcdesigns/iOS-WP-OAuth/blob/master/iOS%20WP%20OAuth/OAuthWP.swift

这是请求:

import 'package:http/http.dart';

ajaxPost() async {

    String apiURL = "http://example.com/app/oauth/authorize";
    String username = 'admin';
    String password = 'pass';

    final identifier = "xxxxxxxxxxx";
    final secret = "xxxxxxxxxxx";

    var requestBody = {
      'client_id': identifier,
      "user_login": username,
      "user_password": password,
      'wpoauth_login': "1",
    };

    var headers = {
      'Accept': 'application/json',
    };

    Response r = await post(
      apiURL,
      body: requestBody,
      headers: headers
    );
    print(r.statusCode);
    print(r.body);

    var reqBody = {
      'client_id': identifier,
      'ios_wp_oauth': '1',
      'response_type': 'code',
    };

    String rawCookie = r.headers['set-cookie'];
    if (rawCookie != null) {
      int index = rawCookie.indexOf(';');
      headers['cookie'] =
          (index == -1) ? rawCookie : rawCookie.substring(0, index);
    }

    Response res = await post(
      apiURL,
      body: reqBody,
      headers: headers
    );

    print(res.statusCode);
    print(res.body);
}

【问题讨论】:

    标签: http post oauth-2.0 dart flutter


    【解决方案1】:

    查看requests

    • 截至目前,它使用 shared_preferences 这不是存储敏感数据(会话 ID 等)的最佳实践(安全方面)Issue #1

    pubspec.yaml

    dependencies:
      requests: ^1.0.0
    

    用法:

    import 'package:requests/requests.dart';
    
    ajaxPost() async {
        // this will persist cookies
        await Requests.post("http://example.com/app/oauth/authorize", body: {"username":"...", "password":"..."} ); 
    
        // next requests will re-use the persisted cookies
        dynamic data = await Requests.get("http://example.com/app/foo", json: true); 
    }
    

    【讨论】:

    • 顺便说一句 - 我强烈建议您使用 https
    • 它不支持MultipartFile请求,这是基本需求。
    • @Sateesh - 这不是投反对票的理由。如果缺少特定功能,您可以在我的 repo 中打开 PR
    • 好的,我将撤消反对票。我已经重构了依赖于Requests 的整个代码,不幸的是我使用了Dio
    • @Jossef Harush 你好))对不起,我还没有使用你的包,但问题是:你是如何处理并行请求的?因为他们都在更新cookie。你会冻结第二个请求直到第一个请求结束吗?
    猜你喜欢
    • 2013-10-24
    • 2013-10-06
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    相关资源
    最近更新 更多