Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to depict sessions in api blueprint format?

I am currently trying to depict a existing API with apiary.io. The system implements authentication via a login request that returns a http-cookie containing a session-id.

As far as I know it is standard that a browser sends all http-cookies he previously received from a host back to him when making another request.

It seems, this isn’t done by Dredd when running a test generated by my blueprint file. And because of this any requests that needs the user to be logged in do not work correctly for the test.

Is there a possibility to mark a request as “needs to be before running this request” respectively to force Dredd to manage these http-cookies?

BTW, the REST service is implemented in Sails.js, a mvc-framework for node.js.

like image 445
Florian Loch Avatar asked May 06 '14 21:05

Florian Loch


1 Answers

This is old but I just ran into the same issue and the dredd docs are quite out of date (isn't that ironical?!), so since I figured it out this may help someone :)

You can read and overwrite response and request body and headers using hooks (this is the most up to date page I found on the topic but still has issues and typos). One caveat is that dredd doesn't seem to have helpers for cookies so you have to parse and build cookie headers yourself.

In my case the sessionId comes back in the json body as well as as a cookie: I parsed the body since that's easier but you could very well retrieve the session from the response cookie if needed. Here is roughly the hooks I wrote to make auth work:

hooks = require('hooks');
stash = {}

// hook to retrieve session on a login
hooks.after('Auth > /remoteauth/userpass > POST', function(transaction){
  stash['token'] = JSON.parse(transaction.real.body)['sessionId'];
});

// hook to set the session cookie in all following requests
hooks.beforeEach(function(transaction){
  if(stash['token'] != undefined){
    transaction.request['headers']['Cookie'] = "id=" + stash['token']
  };
});

The docs explain how to set up the hooks, although one thing that tripped me is that the dredd --names command doesn't work if you have a dredd.yml file in the same directory (seems like the presence of the file makes dredd ignore all command line arguments).

like image 119
Jules Olléon Avatar answered Oct 25 '22 03:10

Jules Olléon