How to pass cookie/session id in dio resquest?

4k Views Asked by At

I am wandering that how could I send my session Id from login to other rest api calls in flutter. My Situation here is I want to have a login screen and Products list page. I get success with developing Login page with authentication. Here is the code snippet

Login Button:

 RaisedButton(
          onPressed: () {
            ApiProvider().userLogin().then((value) => {});
          },
          child: Text('Login'),
        )

ApiProiver.dart :

 Future userLogin() async {
   var options = Options(
    headers: {"Content-Type": "application/json"},
   );
  var body ={
   "jsonrpc" : "2.0",
   "params":{
    "login":"admin",
    "password":"admin",
    "db":"food_app"
  }
 };

 Response response = await dio.post('http://food_app.com/web/session/authenticate',options:options, 
 data: body);
 print("Response $response");
 final cookies = response.headers.map['set-cookie'];
 print("Cookie,$cookies");
}

Output:

  Response :

  {"jsonrpc": "2.0", 
    "id": null,
    "result": 
            {"uid": 2, 
             "is_system": true, 
             "is_admin": true, 
             "db": "food_app",   
            "name":  "Administrator", 
            "username": "admin", 
           "web.base.url": "http://food_app.com",
   }
 }

Cookie :

[session_id=d446d3ef6bd536ef8e0bf6f1c9ba3a40c92ccb99; Expires=Thu, 21-Jan-2021 08:59:42 
GMT; Max-Age=7776000; HttpOnly; Path=/]

Result is ok!!!!!!!!!!!!!!!

I get cookies/session id from the above code now my question is how could I pass the session id to the next api calls

Future fetchProducts() async {
 var options = Options(
   headers: {"Content-Type": "application/json"},
  );
  var body =
     {
       "jsonrpc" : "2.0",
      "params":{ }
     };
  Response response = await dio.post('http://food_app.com/api/get_products',options: options, data:body );
  }

Here is the python test scripts which accepts the above api call :slight_smile:

 odoo_url = "https://food_app.com"

 headers = {'Content-type': 'application/json'}

 myobj = {"jsonrpc":"2.0","params":{'db':'food_app','login':'admin','password':'admin'}}
     
 session_details = requests.get(url=odoo_url + '/web/session/authenticate', data=json.dumps(myobj), 
                                  headers=headers)
 session_id = str(session_details.cookies.get('session_id'))
 print("Session id")
 print(session_id)
 cookies = {
 'session_id': session_id
}    

#LIST ALL PRODUCTS GET METHOD

 url_get = 'http://food_app.com/api/get_products'
 headers = {'Content-type': 'application/json'}
get_products = requests.get(url_get, cookies=cookies)
json_data = json.loads(get_products.text)
for product in json_data['response']:
  print(product['name'])

the above python code hits the api and return the correct response

Session :
8a1f03ff94459c6a30d3be6cbdf3e8ca9b1ee23c

Product Names:
Calamari & Rice in Orange Souce
Chicken Wings in Buffalo Sauce
Mixed Vegatables, Paprika & Chips - Dish 1
New York Strip Steak  
Roasted Brussels Sprout Salad
Salmon in Carrot Souce
Vegetable Salad with Avocado & Rice

Please edit my fetchProducts() method in order to get the response from api with session.

1

There are 1 best solutions below

0
On

You need to use cookie manager

Example

import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:cookie_jar/cookie_jar.dart';

main() async {
  var dio =  Dio();
  var cookieJar=CookieJar();
  dio.interceptors.add(CookieManager(cookieJar));
  
  // first request, and save cookies (CookieManager do it).
  await dio.get("https://baidu.com/");
  
  // Print cookies
  // print(await cookieJar.loadForRequest(Uri.parse("https://baidu.com/")));

  // second request with the cookies
  await dio.get("https://baidu.com/");
  ... 
}