Set sessionStorage to prevent refresh to login

I’m using vue-cli and I’m trying to figure out a way that when the user is logged in, if they refresh the page they aren’t auto brought back to the login but when they exit off the webpage and reopen they are brought back to the login.

My login page sends username and password to an api via axios and if it is in the api the user is logged in.

I’m looking into Windows.sessionStorage and vue-sessionStorage

I see I can add a session storage like so:

this.$session.set('username', username);

but I’m not sure exactly how to implement it so it prevents refresh to login.

Any help would be appreciated, thanks so much!

Never used Vue cli, but the way you are describing your issue seems a case of client-side routing.

I guess the workaround would be what vue calls navigation guards ; following their documentation:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        //  if not auth go to Login
       if (!isAuthenticated) next({ name: 'Login' })
      else next() // else enter route
      }
    }
  ]
})

Of course be aware of the usual security risk :slight_smile:

@Marmiz thanks so much for your help! I tried implementing the Navigation Guard but I got a bit stuck on how to add isAuthenticated.

Currently in my login page I send the logged in user using this.$router.replace({ name: "HomePage", params: {login: res.data.name, id: res.data.id } });:

methods: {
   postNow: async function() {
      try {
        const res = await  axios.post('url/api/login/',  {
          username: this.input.username,
          password: this.input.password
         },{withCredentials: true}, {headers: {
              'Content-type': 'application/json',
            }}, ).then(res => res.data);
          if(this.input.username != "" && this.input.password != "") {
            if(this.input.username == res.data.name && this.input.password == res.data.password) {
              this.$router.replace({ name: "HomePage", params: {login: res.data.name, id: res.data.id } });
            } else {
                alert("The username and / or password is incorrect");
                // e.preventDefault();
              }
          } else {
              console.log("A username and password must be present");
            }
        } catch (err) {
          this.showInvalidMessage = true
            // alert("The username and / or password is incorrect");
        }

I tried adding to my router:

routes: [
    {
      path: '/',
      name: 'HomePage',
      component: HomePage,
      props: true,
      beforeEnter: (to, from, next) => {
       if (!authenticated) next({ name: 'Login' })
       else next() 
       }
    },

but where can I set authenticated?
Otherwise I get an error:

ReferenceError: authenticated is not defined

Thanks so much!

That depends a lot on your site, needs and limitations.

As you said at the beginning, you could simply add a value into SessionStorage, then your isAuthenticated becomes a simple check if that value exist.

You can imagine that this topic becomes real complicated, nowadays many websites uses a mix of token in cookies as well as JWT to determine if a user is authenticated as well an maintain high level of security.

For example look at this thread on SO:

Good luck and happy coding :sparkles:

@Marmiz thanks so much!

So if I understand correctly I could do something like:

this.$session.set('isAuthenticated", isAuthenticated);

and then in the router:

beforeEnter: (to, from, next) => {
       if (!isAuthenticated) next({ name: 'Login' })
       else next() 
       }

Thanks so much for the link!