1

I have created a NUXT.JS content static site served with .md files. Now i want to add authentication to it. I want to redirect a user form my main site which is built in VUE.JS

User have to login to my main site and then clicking on a link -> redirect the user to nuxt site

Here are my nuxt configs:

import theme from '@nuxt/content-theme-docs'

export default theme({
docs: {
primaryColor: '#E24F55'
},
content: {
liveEdit: false
},
buildModules: [
'@nuxtjs/color-mode'
],
colorMode: {
preference: '', // default value of $colorMode.preference
fallback: 'light', // fallback value if not system preference found
hid: 'nuxt-color-mode-script',
globalName: '__NUXT_COLOR_MODE__',
componentName: 'ColorScheme',
classPrefix: '',
classSuffix: '-mode',
storageKey: 'nuxt-color-mode'
},
})

-------->>>>>>>>

    In middleware>stats.js
    
    export default function ({ route, redirect }) {
    console.log('route', route)
    // api call to check further
   }




nuxt.config.js
   import theme from '@nuxt/content-theme-docs'

export default theme({
  docs: {
    primaryColor: '#E24F55'
  },
  modules: ['@nuxtjs/axios'],
  
  router: {
    middleware: 'stats'
  }
})

image

Abhishek Matta
  • 218
  • 3
  • 15
  • It is difficult to answer this question because we do not know what your authentication looks like. Basically, https://auth.nuxtjs.org/ is suitable for any kind of authentication. – 4ern Feb 25 '21 at 10:15
  • I know this plugin but I don't have any vue file. I have just created static md files using @nuxt/docs theme and now I want to check if user is logged in to my site or not before serving the content – Abhishek Matta Feb 25 '21 at 10:21
  • You can protect your `@nuxt/docs-theme` behind a `@nuxt/auth` middleware using Auth0 by targetting your app to serve an SPA only. Not sure about the other Vue site tho.. – kissu Feb 25 '21 at 10:23
  • @kissu, Thanks for replying. Is there any example you can show me so that I can follow the steps – Abhishek Matta Feb 25 '21 at 10:25
  • @nuxt/docs theme is nothing else than a nuxt application. You can also create middleware, plugins & components in it. You can then perform your authentication there. – 4ern Feb 25 '21 at 10:26
  • @4ern It would be great if you can show me a working example because I'm very new to this. – Abhishek Matta Feb 25 '21 at 10:29
  • I can share a repo I made for my girlfriend. Just gonna need to strip the private info and explain a bit the configuration of Auth0. Will probably share it today. – kissu Feb 25 '21 at 12:10
  • @kissu cool. It would be a great help thanks. – Abhishek Matta Feb 25 '21 at 12:12
  • @kissu Yes, It did helped me a lot. Thanks. – Abhishek Matta Mar 02 '21 at 08:38
  • @4ern Your example helped me and I'm able to make it work Thanks a ton. Do you know why axios in nuxt sending my object as a string if I'm passing the object in body? – Abhishek Matta Mar 02 '21 at 08:40
  • This is normal with axios and other frameworks, that json strings are sent. What you probably want is a form dataset, as you are used to with php. You can find out exactly how this works [here](https://stackoverflow.com/a/22783314/6725944) – 4ern Mar 02 '21 at 08:54
  • So, internally axios must be using JSON.stringify is this correct? – Abhishek Matta Mar 02 '21 at 09:02

3 Answers3

2

Here is a local/jwt example of how to use nuxt-auth in @nuxt/docs theme.

The file structure:

├───components
│   └───global
         auth.vue
├───content
│   └───en
         playground.md
├───node_modules
├───nuxt.config
├───package.json
├───static
// nuxt.config.js

import theme from "@nuxt/content-theme-docs";

export default theme({
  docs: {
    primaryColor: "#E24F55",
  },

  content: {
    liveEdit: false,
  },

  buildModules: ["@nuxtjs/color-mode"],

  colorMode: {
    preference: "", // default value of $colorMode.preference
    fallback: "light", // fallback value if not system preference found
    hid: "nuxt-color-mode-script",
    globalName: "__NUXT_COLOR_MODE__",
    componentName: "ColorScheme",
    classPrefix: "",
    classSuffix: "-mode",
    storageKey: "nuxt-color-mode",
  },

  // ---->
  auth: {
    strategies: {
      local: {
        token: {
          property: "token",
          // required: true,
          // type: 'Bearer'
        },
        user: {
          property: "user",
          // autoFetch: true
        },
        endpoints: {
          login: { url: "/api/auth/login", method: "post" },
          logout: { url: "/api/auth/logout", method: "post" },
          user: { url: "/api/auth/user", method: "get" },
        },
      },
    },
  },
  // <----
});

// components/global/auth.vue
<template>
  <div>
    <form @submit.prevent="userLogin">
      <div>
        <label>Username</label>
        <input type="text" v-model="login.username" />
      </div>
      <div>
        <label>Password</label>
        <input type="text" v-model="login.password" />
      </div>
      <div>
        <button type="submit">Submit</button>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      login: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    async userLogin() {
      try {
        let response = await this.$auth.loginWith('local', { data: this.login })
        console.log(response)
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

and in your *.md file use the auth component:

---
title: Playground
description: ''
position: 1
category: Playground
---

<auth></auth>

This example is quite simple. It is only meant to show how to use nuxt auth in the nuxt docs theme.

4ern
  • 965
  • 1
  • 9
  • 21
  • Is there any way that before the page is served I can hit an api to check if user's is logged in or not (just like we have beforeEach Route hook in VUE JS)? Note I dont want a log-in page in the nuxt project. User will be login in our vue project and from there on clicking a link he'll be redirected to the nuxt project(url) – Abhishek Matta Feb 25 '21 at 12:16
  • In nuxt, the middleware serves as a beforeEach route. You can place your logic there. – 4ern Mar 02 '21 at 08:44
  • I think middleware works on pages or group of pages and in my case it is .md files. So when trying to define a middleware It's throwing error: "Unknown middleware stats" – Abhishek Matta Mar 03 '21 at 08:36
  • middleware is executed at the very beginning. can you show me how you implemented the middleware? – 4ern Mar 03 '21 at 13:18
  • Hi, I have added the code in question.Please have a look at it. – Abhishek Matta Mar 03 '21 at 13:47
1

I've spent some time redacting how to do it. Unfortunately I could not make proper edited and annotated screenshots of the Auth0 (too cumbersome with my current setup to make something clean) but here is my github repo with all the explanations on how to make this work.

https://github.com/kissu/so-nuxt-docs-theme-auth-auth0

kissu
  • 40,416
  • 14
  • 65
  • 133
1

oh ok, you're right, he can't register the middleware. But you can create a plugin with beforeEach.

// plugins/guard.js

export default ({ app }) => {
    app.router.beforeEach((to,from, next) => {
        console.log(to, from)
        next()
    })
}

// nuxt.config.js

// ...

plugins: [__dirname + '/plugins/guard.js'],

// ...
4ern
  • 965
  • 1
  • 9
  • 21