Search code examples
authenticationcookieshapi.jshapi

Unable to authenticate a user using @hapi/cookie 19.x.x


I've recently upgraded my project to use hapi 19.x.x along with that I have updated the project to use @hapi/cookie as opposed to the deprecated hap-auth-cookie however after successful authentication my application constantly tries to reauthenticate even after setting a session cookie with request.cookieAuth.set({ id : id})

When the application is redirected to the 'restricted page' using the redirectTo: property on the .auth.strategy('admin', 'cookie', {}) object.

I noticed that the state on the incoming request is {} empty when it shouldn't be

node -v // 12.16.2

Google Chrome Version 80.0.3987.163 (Official Build) (64-bit)

package.json {

    "dependencies": {
    "@hapi/catbox-redis": "5.0.5",
    "@hapi/cookie": "11.0.1",
    "@hapi/h2o2": "9.0.1",
    "@hapi/hapi": "19.1.1",
    "@hapi/inert": "6.0.1",
    "@hapi/joi": "17.1.1",
    "@hapi/scooter": "6.0.0",
    "@hapi/wreck": "17.0.0",
}
server.auth.strategy('admin', 'cookie', {
    cookie: {
        name: Server.cookieName,
        password: auth_cookie_password,
        isSecure: false,
        ttl: Server.cacheCookieTtlMs
    },
    appendNext: true,
    redirectTo: outboundUrl,
    validateFunc: async (request: any, session: any) => {

    // blah blah

    }
      {
        method: ['GET', 'POST'],
        path: '/login',
        options: {
          auth: false,
          security: true
        },
        handler: async (request: any, h) => {
          try {

            const tokenSet = await authCallback();

            const session = {
              id: tokenSet.id,
            }

            request.cookieAuth.set(session);

            const returnScript = `<script type="application/javascript" >(function() { setTimeout(function() {window.location = "http://localhost:3000"})})()</script>`;


            return h.response(returnScript)
          } catch (e) {
            return h.response('Internal server error').code(500)
          }
        }
      }

any help would be appreciated.


Solution

  • you have to set the cookie path to /

    Cookies are only sent to the server when the URL of the request starts with the value of the cookie’s path. When you omit path, the default is the URL of the request that received the response with the Set-Cookie header. So, let’s say you omit path and your cookie is set on a URL like https://example.com/login (which is very common), then the cookie will only be sent on requests for subpaths like https://example.com/login/foo, which is almost never what you want.