1

Noob in authentication and having issue with nuxt auth cookie strategy.

My backend is golang, and I set cookie after successful login

    http.SetCookie(w, &http.Cookie{
        Name:     "session_token",
        Value:    sessionToken,
        Path:     "/",
        HttpOnly: true,
    })

saw that there was issues with httpOnly, but this is not impacting my problem.

I have minimal configuration at the moment.

  auth: {
    strategies: {
      cookie: {
        endpoints: {
          login: { url: "/api/auth/login", method: "post" },
          logout: false, // will be implemented
          user: false,   // will be implemented
        },
      },
    },
  },

My issue is that I set session cookie, which means that it is unset after browser is closed (at least that's how I understand it). But it seems that nuxt doesn't care if there is cookie or not.

Log in works fine - I get loggedIn: true. But when cookie is deleted (after browser close) I am still loged in.

if ssr: true I also get this error: [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.

and site hangs.

Is there a way to log out a user when cookie is not present? Or I should rethink my approach?

Tried other config options, like token.required:true etc. Also changing cookie token name with prefixes auth.. But nothing seems to help.

EDIT: this is my code for auth:

<template>
  <div class="layout">
    <form @submit.prevent="userLogin">
      <div>
        <label>Email</label>
        <input type="email" v-model="login.email" />
      </div>
      <div>
        <label>Password</label>
        <input type="password" v-model="login.password" />
      </div>
      <div>
        <button type="submit">Submit</button>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      login: {
        email: "",
        password: "",
      },
    };
  },
  methods: {
    async userLogin() {
      try {
        let response = await this.$auth.loginWith("cookie", {
          data: this.login,
        });
        console.log(response);

        this.$router.push("secret");
      } catch (err) {
        console.log(err);
      }
    },
  },
};
</script>

In header part I have:

    ...
      <nuxt-link
        v-bind:class="{ active: routeName === 'secret' }"
        class="link"
        to="/secret"
        v-if="isAuthenticated"
        >Secret</nuxt-link
      >
    </nav>
    <div class="auth">
      <div v-if="isAuthenticated">
        <a class="link" @click="logout">Logout</a>
      </div>
      <div v-else>
        <nuxt-link
          v-bind:class="{ active: routeName === 'register' }"
          class="link"
          to="/register"
          >Register</nuxt-link
        >
        <nuxt-link class="button" to="/login">Login</nuxt-link>
      </div>
    </div>
   ...
   <script>
    import { mapGetters } from "vuex";

    export default {
    ...
    computed: {
    ...

    ...mapGetters(["isAuthenticated", "loggedInUser"]),
  },
};
</script>

SECOND EDIT:

changed my config to try other variants and probably leaving session cookies behind.

  auth: {
    // cookie: false,
    strategies: {
      local: {
        token: {
          // property: 'session_token',
          // global: true,
          required: false,
          type: false
        },
        endpoints: {
          login: { url: "/api/auth/login", method: "post" },
          logout: false,
          user: false,
        },
      },
    },
  },

but I'm still getting The client-side rendered virtual DOM tree is not matching server-rendered content. When I close and reopen browser. Noticed that this appears only when I have code with v-if="$auth.loggedIn" or v-if="isAuthenticated". Am I doing something wrong? If I wrap it with <client-only> tag it solves the warning, but seems like a hack.

  • unless the cookies are not expired or you set them expired, they wont be deleted by closing browser. So try to check your cookies if they are still being sent in backend. If that is the case and you want them to be removed, set them expired – sigkilled Sep 21 '21 at 19:28
  • Sorry, I realized after I check the part you write cookies closely. You don’t give any expiration date so it makes sense that cookies will be deleted after you closed the browser window. – sigkilled Sep 21 '21 at 19:35
  • I can see that cookie is deleted after browser close. And nuxt auth have default of session expiration (but not sure if that means after browser close). Maybe I should just stick with expiring cookie – Dalius Slamas Sep 22 '21 at 04:58
  • 1
    If you want the user to be logged out when you do leave the page, either watch for the close event on the tab and remove the cookie or wipe the cookie once you do arrive on the page. Also, not sure why you're playing with the `ssr` key here but you should either choose it or not (depending of your project's need) and fix the DOM issue anyway. – kissu Sep 22 '21 at 08:04
  • @kissu but cookie is removed after browser close. I can see that it is not there in devtools->Application->cookies and there is nothing in local storage as well. But I'm still logedIn – Dalius Slamas Sep 22 '21 at 08:19
  • The thing is I'm not even sure how it can detect if cookie is present if there is no config for cookie name (if I set cookie.name I can't even get `loggedIn:true`). – Dalius Slamas Sep 22 '21 at 08:24
  • 1
    Are you still logged in if you try in a private window? Also, check your network and be sure that your cookie/localStorage is related to your dev domain. Also, what is the DOM issue about? Maybe it's a `v-if` of you being logged in and not. Can you please share the related code to the auth? The issue is maybe there rather than in the module. – kissu Sep 22 '21 at 08:28
  • @kissu sorry for late response. It works as expected in incognito mode. How can I check if cookie is related? I'm running on localhost - my go in docker on port 8080 and nuxt on port 3000. I'm not sure about DOM issue. It appears when I log in -> close browser -> open browser -> go to my website. After DOM warn there is random error from client like `TypeError: Cannot read properties of undefined (reading 'toLowerCase')` but after page refresh page loads, and I'm still loged in. – Dalius Slamas Sep 23 '21 at 17:35
  • I edited my question with some auth code – Dalius Slamas Sep 23 '21 at 17:40
  • After removing auth related code, DOM issue disappears. But I can see in vue console that state is still `loggedIn:true strategy:"cookie"` after browser close and cookie is removed – Dalius Slamas Sep 23 '21 at 17:53
  • Did you tried the `local` strategy rather? – kissu Sep 24 '21 at 08:43
  • @kissu local strategy doesn't seem to pick cookie that is returned. It works only when I return token in a response JSON. Is it safe to store tokens in local storage? I mean I'm thinking to just use local storage because I can't figure this one out with cookie. – Dalius Slamas Sep 27 '21 at 16:47

0 Answers0