Vue JS - Keep user logged in after refreshing browser?

Hi,

I recently implemented Auth0 to my webapp and everything is working fine except one part - if a user refreshes the browser, even though a token still exists in memory, I’m logged out. Not entirely sure how to solve this, but below is my code
auth.js:

import auth0 from "auth0-js";
import API from "./API";

const webAuth = new auth0.WebAuth({
  domain: "domainNameHere",
  clientID: clientIdHere,
  responseType: "token id_token",
  audience: audience,
  redirectUri: redirectUri,
  scope: "openid profile email create:projects"
});


let tokens = {};
let userProfile = {};

const login = () => webAuth.authorize();
const logout = () => (tokens = {});
const isLoggedIn = () => {
  return tokens.accessToken && new Date().getTime() < tokens.expiry;
};
const getProfile = () => userProfile;

const handleAuth = callback => {
  webAuth.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
  tokens.accessToken = authResult.accessToken;
  tokens.idToken = authResult.idToken;
  tokens.expiry = new Date().getTime() + authResult.expiresIn * 1000;
  userProfile = {
    profile: authResult.idTokenPayload,
    scope: authResult.scope
  };
  window.location.hash = "";
  // Store the authResult in local storage and redirect the user elsewhere
  localStorage.setItem("access_token", authResult.accessToken);
  localStorage.setItem("id_token", authResult.idToken);
  callback();
} else {
  console.log(err);
}
  });
};

export { login, logout, handleAuth, isLoggedIn, getProfile };

Callback.vue:

import { handleAuth, isLoggedIn, userProfile } from "@/utils/auth";

export default {
  name: "Callback",
  beforeMount() {
    handleAuth(err => {
      if (err) {
        console.log(err);
        return;
      }
      this.$router.push("/");
      this.$store.dispatch("sendLoginStatus", true);
      this.$store.dispatch("getUser");
    });
  },

  data() {
    return {
      isLoggedIn: isLoggedIn()
    };
  },
};

I’m storing most of the information in a Vuex store, which obviously will be removed upon refresh, but how would I keep the user logged in nonetheless?

Hi @erikvmalmberg,

Take a look at this topic:

And checkSession:

https://auth0.com/docs/libraries/auth0js/v9#using-checksession-to-acquire-new-tokens

Hopefully this helps.

Thanks,
Dan

auth0 doesn’t want you using local storage.

How is auth0 itself doing it? Ie on this website? If I refresh the browser right now I’ll still be logged in…

Yes, local storage is not recommended.

Users can remain logged in through a refresh by utilizing a session with the auth server. This is where the checkSession method that I linked in the auth0js doc above comes in.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.