'Nuxt js <nuxt-link /> authentication

I have a route in nuxt that has to be accessible only by logged in users: /dashboard/secret.

In /dashboard page I have a link like this:

<nuxt-link to="/dashboard/secret">Link to "secret" page</nuxt-link>

When clicked, nuxt will fetch that page from

myapp.com/_nuxt/pages_dashboard_secret.js

How can I add authentication for that nuxt route to stop people from manually going to that url and reading the contents?

Yes the actual secret data will be taken from external api which will validate user token, but still it seems wrong that people can see even the html of this page



Solution 1:[1]

if you just want to protect a js file, it would be wrong to do it like this. But if you mean you just want to protect a route from being accessed manually by the users, you must try Nuxt Middlewares and write a middleware for authentication and user fetching.

The middleware structure can be as simple as this:

export default function ({ store, redirect }) {
  // If the user is not authenticated
  if (!store.state.authenticated) {
    return redirect('/login')
  }
}

and you can simply use it like this in your root (or secretPage) layout:

<template>
  <h1>Secret page</h1>
</template>

<script>
export default {
  middleware: 'authenticated'
}
</script>

Solution 2:[2]

You can use nuxt/auth package, that is the case for your work and can be used as a plugin and module, you can check has it for the be accessible page or not, it runs automatically and has semantic structure.

Solution 3:[3]

You cannot keep your secret on client side (in your JS code) everyone using your application can get it from his browser. You need to keep secret keys on server side and make some validation endpoint to provide if user is valid or not or just keep his session after login.

Solution 4:[4]

you can use middleware in nuxt framework. Also, route has a information about url and request. You can make a logic by using them. https://nuxtjs.org/docs/directory-structure/middleware/

middleware/auth.js

export default async function ({store, from, route, req}) {
 if (process.client) {
  if (route.name === 'dashboard-room-id' && from.name === route.name) 
    return
  else await store.dispatch('checkSession', route)
  }
}

Solution 5:[5]

  1. save the token in the store on nuxtServerInit or whenever you get it.
  2. on /dashboard/secret page check in the fetch method if there is a token set.

if token is set, fetch your data otherwise redirect the use somewhere else https://nuxtjs.org/examples/auth-routes/#redirect-user-if-not-connected

Solution 6:[6]

For such a guard of pages, the middleware is the sure way to do it.

  1. Create a middleware file in the middleware directory
  2. Add your middleware logic as described here https://nuxtjs.org/api/pages-middleware/
  3. Then add the middleware option in your page component

Solution 7:[7]

as it is mentioned that the routing should be done on the server, in case you just want to handle it if I have this store/index.js action

async nuxtServerInit({ dispatch, commit }, { req }) {
    try {
      if (process.server && process.static) { return }
      if (!req.headers.cookie) {
        console.log('return ')
        return
      }
      const parsed = cookieparser.parse(req.headers.cookie)
      const accessTokenCookie = parsed.__session
      if (!accessTokenCookie) { return }
      const decoded = JWTDecode(accessTokenCookie)
        if (userData.exists) {
          commit('setState', { name: 'user',
            value: {
              uid: decoded.user_id,
              email: decoded.email,
              ...userData.data()
            } })
        } 
    } catch (e) {
      console.log(e)
    }
  },
//Login firebase
 async fireLogin({ dispatch }, { singInWith, account }) {
    const resp = await this.$firebase.auth()signInWithEmailAndPassword(account.email, account.password)
    const token = await resp.user.getIdToken()
    Cookie.set('__session', token)
    return { email: resp.user.email, uid: resp.user.uid }
 }

Middleware/auth.js

export default function({ store, route, redirect }) {
  const user = store.state.user
  const blockedRoute = /\/admin\/*/g
  const homeRoute = '/'

  if (!user && route.path.match(blockedRoute)) {
    redirect('/')
  }

  /*if (user && route.path === homeRoute) {
    redirect('/admin')
  }*/
}

nuxt.config

router: {
    middleware: [
      'authenticated'
    ]
  },

Solution 8:[8]

you can set the middleware for current page

middle ware

export default context => {
  //set Condition and logic
};

route page :

middleware: 'name of middle ware'

Solution 9:[9]

i can suggest three solutions:

1.Get pathname in your js codes and then check the url that client using to access your page , for example if pathname is /dashboard/secret and user is logged in then show the page

for checking pathname u can use these cods:

$nuxt.$route.path
//or good old pure js ;)
window.location.pathname

2.check if user truly logged in (backend & frontend) for that u can use nuxt-auth and sync it to your backend as well.

for example if you using laravel , u can use laravel passport , in that case when the request sended to the backend route, you can check if user is logged in to the backend as well.

Ps:This way is more secure and of course in every backend language this process can be different, but surely all of them will have the same capability.

3.using .htaccess :

Do not allow the user to view the file directly from the server path Read more

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kissu
Solution 2 Hozhabr
Solution 3 Canor
Solution 4 Namlulu
Solution 5 Bart
Solution 6 Kelvin Omereshone
Solution 7 li x
Solution 8
Solution 9 Arian Fm