How to get a cookie in Flutter Web from header?
Asked Answered
F

2

6

The Flutter Web application send a HTTP REST API POST request and gets back a JSON response and a cookie in the Set-Cookie header as follows.

(Flutter (Channel beta, 1.22.0, on Microsoft Windows)

Set-Cookie header

When the cookie is extracted, the response does not seem find the header value. The call and extraction code is:

var response = await http.post(url, headers: {"Content-Type": "application/json"}, body: jsonEncode(data));

if (response.statusCode == 200) {
  var cookie = response.headers['set-cookie'];
  print('cookie: $cookie');
}

The console result is:

cookie: null

The server side runs on ASPNet.Core 3.1 in a Docker container, however it should not be an issue, since the cookie is there in the header. So, how can I extract it in Flutter Web?

Actually my final goal is to send the cookie back with every other request. But it does not seem to happen automatically in the browser. So it is also a good solution if someone could point out the proper way of handling this scenario.

Any help is appretiated. Thanks.

Fotinas answered 7/10, 2020 at 10:4 Comment(0)
G
16

The question was asked a month ago but my answer might be helpful for someone else. Cookies in Flutter Web are managed by browser - they are automatically added to requests (to Cookie header), if the cookie was set by Set-Cookie previously - more precisely, it works correctly when you do release build. In my case it didn't work during dev builds. My solution:

On server set headers:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:61656

// port number may be different

In flutter: class member:

final http.Client _client = http.Client();

// example

Future<String> getTestString() async {
    if (_client is BrowserClient)
      (_client as BrowserClient).withCredentials = true;
    await _client.get('https://localhost/api/login');
    await _client.get('https://localhost/api/login');
    return 'blah';
  }

http.Client() creates an IOClient if dart:io is available and a BrowserClient if dart:html is available - in Flutter Web dart:html is available. Setting withCredentials to true makes cookies work.

Run your app:

flutter run -d chrome --web-port=61656

// the same port number that on server

Remember that in Flutter Web network requests are made with browser XMLHttpRequest.

Gemperle answered 27/11, 2020 at 15:23 Comment(10)
Thanks for the answer. I have solved my problem already by using bearer tokens as a workaround but next time I will use this solution.Fotinas
This answer really saved me today, thanks. This works great for my use case.Arctic
BrowserClient is not defined, Which package provided it?Revisionist
import 'package:http/browser_client.dart'; for BrowserClientRevisionist
I tried these steps (Chrome release mode, setting server headers, using http.Client and enabling withCredentials), but no luck. Still no cookies.Versicular
I was finally able to make it work with 2 additional cookie properties set on server (I am using Akka-server).SameSite=None and Secure=true . One should be able to set these properties while doing setCookie on server. Also we need ssl communication with server.Versicular
withCredentials didn't helped. Still response.headers['set-cookie'] is not set.Kevenkeverian
Needs to bold this text Cookies in Flutter Web are managed by browser. I realized I don't need to access cookies at all.Hibernate
In my case cookies are not handled by the browser. Still looking for a solutionMartinamartindale
This solution does not work.Sulfonate
G
0

There is no need to handle cookies in flutter web. Each api request from browser it will automatically added to header. If you use cross origin (app server domain and frondend domain are different), you need to configure your app server like node/express js

const cors = require('cors');

app.use(cors({
   origin: ["https://yourapidomain.com"],
   methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
   credentials : true // allows cookies
}));

In flutter, use http plugin like below

import 'package:http/browser_client.dart';

class ApiService {

   Future<Response> fetchRequest(
      {required String url, required Map<String, dynamic>? data}) async {
     Client client = BrowserClient()..withCredentials = true;
     return await client.post(Uri.parse(url), body: data);
   }

}

BrowserClient uses XMLHttpRequest. its working fine in production for me. Make sure your cookie value is below format

NAME=w&ddsfsfsfgretdv464565yfbr555yhf; Domain=.yourapidomain.com; Path=/; Expires=Thu, 01 Aug 2024 01:00:00 GMT; HttpOnly
Glanders answered 9/8 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.