Coder Social home page Coder Social logo

Cookie authentication about frisby HOT 17 CLOSED

vlucas avatar vlucas commented on July 25, 2024
Cookie authentication

from frisby.

Comments (17)

grtjn avatar grtjn commented on July 25, 2024 1

It looks like the frisby api changed a bit in the past couple of years. For posterity, I did it just now using:

    return frisby.fetch(loginUrl, {
      method: 'POST',
      body: JSON.stringify({
        username: 'myuser',
        password: 'mypass'
      }),
      credentials: 'same-origin'
    })
       ...
      .then(function(res) {
        return frisby.fetch(statusUrl, {
          method: 'GET',
          headers: {
            cookie: res.headers.get('set-cookie')
          },
          credentials: 'same-origin'
        })
          ...;
      });
  });

from frisby.

cboden avatar cboden commented on July 25, 2024

From my experience Frisby passes cookies on to subsequent requests automatically.

from frisby.

jozzhart avatar jozzhart commented on July 25, 2024

I am able to get my tests to pass if I manually set the header cookie to a value that I generate via the browser.

But I get Unauthorized if I do not manually assign a cookie session value.

from frisby.

cboden avatar cboden commented on July 25, 2024

Are you nesting your tests?

frisby.create('le Test')
    .post('loginUrl', {user: 'hello', pass: 'world'})
    .after(function() {
        frisby.create('Test private url')
            .get('privateUrl')
            .expectStatus(200)
        .toss()
    })
.toss()

from frisby.

jozzhart avatar jozzhart commented on July 25, 2024

Certainly am.

frisby.create('POST Login as admin')
  .post(URL +'api/login', { username: 'xxxxxx', password: 'xxxxxx', eventId: 11})
  .afterJSON(function(response) {

    frisby.create('Get schools')
    .get(URL +'api/schools')
    .expectJSONTypes('*', {
      name: String,
      coordinator: Object,
      principal: Object,
      user: Object
    })
    .toss();
  })
.toss();

from frisby.

jozzhart avatar jozzhart commented on July 25, 2024

Just found the .afterJSON also passes the actual NodeJS response object, after the body, i.e. .afterJSON(function(body, res) {}); Looking through that I can see the cookie is being passed back:

headers:
{ 'x-powered-by': 'Express',
  pragma: 'no-cache',
  expires: '0',
  'cache-control': 'no-cache, no-store, must-revalidate',
  'content-type': 'application/json; charset=utf-8',
  'content-length': '275',
  'set-cookie': [ 'connect.sid=s%3Am15drFwJIJtwg1Zw5_s8LMXX.ZLCcnJHHSraMemvbpsmjDjb7N2z9ytdGd27DNsN1XoM; Path=/; HttpOnly' ],
  date: 'Wed, 24 Jul 2013 15:44:41 GMT',
  connection: 'keep-alive' 
},

from frisby.

vlucas avatar vlucas commented on July 25, 2024

You just need to set the header manually when you perform the next request using addHeader. Something like this:

frisby.create('POST Login as admin')
  .post(URL +'api/login', { username: 'xxxxxx', password: 'xxxxxx', eventId: 11})
  .afterJSON(function(response, res) {

    frisby.create('Get schools')
    .get(URL +'api/schools')
    .addHeader('Set-Cookie', res.headers['set-cookie'])
    .expectJSONTypes('*', {
      name: String,
      coordinator: Object,
      principal: Object,
      user: Object
    })
    .toss();
  })
.toss();

from frisby.

vlucas avatar vlucas commented on July 25, 2024

Also note that, in general, APIs should be stateless, so they really shouldn't be setting cookies (most API integrations don't store and re-send cookie headers). If you're using OAuth, you should only have to send an access_token parameter with each subsequent response. It's a bit like a session id, only it doesn't involve headers.

from frisby.

jozzhart avatar jozzhart commented on July 25, 2024

Thanks Vlucas & cboden, got it to work using this.

frisby.create('POST Login as admin')
  .post(URL +'api/login', { username: 'xxxxxxxx', password: 'xxxxxxxx', eventId: 11})
  .after(function(body, res) {

    //  Grab returned session cookie
    var cookie = res.headers['set-cookie'][0].split(';')[0];

    frisby.create('Get school details')
    //  Pass session cookie with each request
    .addHeader('Cookie', cookie)
    .get(URL +'api/school')
    .expectJSONTypes({
      name: String,
      coordinator: Object,
      principal: Object,
      user: Object
    })
    .toss();
  })
.toss();

from frisby.

jozzhart avatar jozzhart commented on July 25, 2024

I agree Vlucas, a true RESTful api should be stateless, and use OAUTH or similar to manage authentication.

from frisby.

AoDev avatar AoDev commented on July 25, 2024

Just wanted to share my solution if someone else comes here.I had the same problem.
In my case, the cookie sent by the server is a 3 elements array in res.headers['set-cookie'].

So I did the following:

var setCookie = res.headers['set-cookie']
var cookie = ''

if (Array.isArray(setCookie)) {
    for (var i = 0, len = setCookie.length; i < len; i++) {
        cookie += setCookie[i].split(';')[0]
        if (i < len - 1)
            cookie += '; '
    }
}

from frisby.

mostly-novice avatar mostly-novice commented on July 25, 2024

thank you thank you guys!!

@jozzhart - this line: .addHeader('Cookie', cookie) really helped me out.

from frisby.

JesusLopezCh avatar JesusLopezCh commented on July 25, 2024

Really really helpful!

Thanks 💃

from frisby.

nuno-innoflair avatar nuno-innoflair commented on July 25, 2024

Exactly what I was looking for! Thx!

from frisby.

Jjarrard avatar Jjarrard commented on July 25, 2024

same with mostly-novice ".addHeader('Cookie', cookie)" saved my life.

from frisby.

 avatar commented on July 25, 2024

can the get request be used with the .addHeader('xxx', xxx) command?

from frisby.

vlucas avatar vlucas commented on July 25, 2024

@bradleywhit Yes, of course - and it is in the code above.

from frisby.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.