如何在Flutter中通过Cookie或会话进行发布?

时间:2019-01-04 14:25:03

标签: http post oauth-2.0 dart flutter

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

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

在第一个请求成功后,我获得了登录名和Cookie。但是在第二个请求中,我尝试在标头中设置响应的cookie并获取令牌,但响应为302,我认为未在标头或类似的东西中设置cookie或会话。

快速工作版本:

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);
}

1 个答案:

答案 0 :(得分:0)

签出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); 
}