1
votes

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

6
It is js file. It can even be hosted on CDN. You dont protect js files from access..Aldarund

6 Answers

15
votes

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>
7
votes

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.

4
votes

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.

0
votes
  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

0
votes

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
0
votes

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'
    ]
  },