Giter Club home page Giter Club logo

Comments (13)

hueniverse avatar hueniverse commented on August 30, 2024

Is the password the only thing that's changing between restarts?

from cookie.

jdarling avatar jdarling commented on August 30, 2024

Only thing that changes is the password.

from cookie.

hueniverse avatar hueniverse commented on August 30, 2024

What's the exact behavior?

This is how it should work as you an see from the tests:

  1. bring up app first time
  2. user logs in and gets a cookie
  3. bring up app second time with new password
  4. user logs in with old cookie and gets error along with cookie removed
  5. user logs in again and gets new cookie

from cookie.

jdarling avatar jdarling commented on August 30, 2024

Sorry it took me so long to get back to this. What happens when I try it is:

  1. Start app for first time
  2. Log in and get cookie
  3. Restart app, gets a new password
  4. Refresh page, see "Bad cookie value" response.
  5. Open developer tools and see that the cookie is still there.
  6. Refresh page, go to step 4 :(

In the end, the cookie never gets removed so the user never gets a new cookie.

This is the easiest example:

var Hapi = require('hapi');

var users = {
    john: {
        id: 'john',
        password: 'password',
        name: 'John Doe'
    }
};

var home = function (request, reply) {

    reply('<html><head><title>Login page</title></head><body><h3>Welcome '
      + request.auth.credentials.name
      + '!</h3><br/><form method="get" action="/logout">'
      + '<input type="submit" value="Logout">'
      + '</form></body></html>');
};

var login = function (request, reply) {

    if (request.auth.isAuthenticated) {
        return reply.redirect('/');
    }

    var message = '';
    var account = null;

    if (request.method === 'post') {

        if (!request.payload.username ||
            !request.payload.password) {

            message = 'Missing username or password';
        }
        else {
            account = users[request.payload.username];
            if (!account ||
                account.password !== request.payload.password) {

                message = 'Invalid username or password';
            }
        }
    }

    if (request.method === 'get' ||
        message) {

        return reply('<html><head><title>Login page</title></head><body>'
            + (message ? '<h3>' + message + '</h3><br/>' : '')
            + '<form method="post" action="/login">'
            + 'Username: <input type="text" name="username"><br>'
            + 'Password: <input type="password" name="password"><br/>'
            + '<input type="submit" value="Login"></form></body></html>');
    }

    request.auth.session.set(account);
    return reply.redirect('/');
};

var logout = function (request, reply) {

    request.auth.session.clear();
    return reply.redirect('/');
};

var server = new Hapi.Server('localhost', 8000);

var uuid = function(){
  var rand = function(count){
    var out = '', i=0;
    for (; i<count; i++) {
      out += (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    return out;
  }
  return rand(2)+'-'+rand(1)+'-'+rand(1)+'-'+rand(1)+'-'+rand(3);
};

server.pack.register(require('hapi-auth-cookie'), function (err) {

    server.auth.strategy('session', 'cookie', {
        password: uuid(),
        cookie: 'sid-example',
        redirectTo: '/login',
        isSecure: false
    });

    server.route([
        {
            method: 'GET',
            path: '/',
            config: {
                handler: home,
                auth: 'session'
            }
        },
        {
            method: ['GET', 'POST'],
            path: '/login',
            config: {
                handler: login,
                auth: {
                    mode: 'try',
                    strategy: 'session'
                },
                plugins: {
                    'hapi-auth-cookie': {
                        redirectTo: false
                    }
                }
            }
        },
        {
            method: 'GET',
            path: '/logout',
            config: {
                handler: logout,
                auth: 'session'
            }
        }
    ]);

    server.start();
});

Start it, log in. Refresh the page see that it works. Restart the server. Refresh the page. Get error no matter what:

{
statusCode: 400,
error: "Bad Request",
message: "Bad cookie value: sid-example"
}

from cookie.

hueniverse avatar hueniverse commented on August 30, 2024

Your example doesn't actually set clearInvalid...

from cookie.

jdarling avatar jdarling commented on August 30, 2024

Sorry, minor typo when I was copying from the doc's page to here, should have been:

    server.auth.strategy('session', 'cookie', {
        password: uuid(),
        cookie: 'sid-example',
        redirectTo: '/login',
        isSecure: false,
        clearInvalid: true
    });

Following the same pattern get the same results. Cookie never cleared.

I plan on looking into this but it isn't actually causing me any harm at this point.

from cookie.

jdarling avatar jdarling commented on August 30, 2024

Actually placing some logging messages in scheme.authenticate it never gets called with the invalid cookie. So I'm guessing before scheme.authenticate gets called something internal to Hapi is trying to decode the cookie, seeing it as invalid and returning the error:

{
statusCode: 400,
error: "Bad Request",
message: "Bad cookie value: sid-example"
}

Found it, in lib/index.js on line 34 you copy the configuration object:

    var cookieOptions = {
        encoding: 'iron',
        password: settings.password,
        isSecure: settings.isSecure !== false,                  // Defaults to true
        path: '/',
        isHttpOnly: settings.isHttpOnly !== false               // Defaults to true
    };

but never copy the clearInvalid flag. Changing the above code to:

    var cookieOptions = {
        encoding: 'iron',
        password: settings.password,
        isSecure: settings.isSecure !== false,                  // Defaults to true
        path: '/',
        isHttpOnly: settings.isHttpOnly !== false,               // Defaults to true
        clearInvalid: settings.clearInvalid
    };

Resolves the issue. I'll put together a PR and test case tomorrow if I have some time.

from cookie.

jdarling avatar jdarling commented on August 30, 2024

PR #37 37 fixes this

from cookie.

jdarling avatar jdarling commented on August 30, 2024

I really need to learn to use Github better :(

from cookie.

bsiddiqui avatar bsiddiqui commented on August 30, 2024

@hueniverse if the auth mode is try why do you still get the Bad Cookie Value error? Docs state that with "'try' invalid authentication is accepted, and the user will still reach the route handler," but I've found that the server responds with the error still.

from cookie.

hueniverse avatar hueniverse commented on August 30, 2024

@bsiddiqui while this can go either way, I agree with you that the better response is a 401 not 400. This is fixed in #40

from cookie.

bsiddiqui avatar bsiddiqui commented on August 30, 2024

@hueniverse awesome

from cookie.

lock avatar lock commented on August 30, 2024

This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.

from cookie.

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.