How to POST in Flutter with cookie or session?

Viewed 9784

I'm trying to send a post request in Flutter with http.

and I want to use OAuth2 to login to a self hosted WordPress installation.

At the first request it goes success and I get login and get cookie. But in the second request i try to set responded cookie in the header and get token but response is 302 and I think cookie or session don't set in the header or something like this.

Swift working version:

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

Here is the request:

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 Answers

Check out requests

  • as of now, it uses shared_preferences which is not the best practice (security-wise) to store sensitive data (session-ids etc) Issue #1

pubspec.yaml

dependencies:
  requests: ^1.0.0

Usage:

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