Adding auth to nuxt

Adding auth to nuxt

Ref

  1. Nuxt auth

Setup

  1. Add nuxt-auth and axios:
1
2
yarn add --exact @nuxtjs/auth-next
yarn add @nuxtjs/axios
  1. Config nuxt.config.js:
1
2
3
4
5
6
7
8
9
{
modules: [
'@nuxtjs/axios',
'@nuxtjs/auth-next'
],
auth: {
// Options
}
}
  1. If using Typescript, add @nuxtjs/auth-next to tsconfig.json:
1
2
3
4
5
6
7
{
compilerOptions: {
"types": [
"@nuxtjs/auth-next",
]
},
}
  1. Add auth to route:
  • Per route, add to .vue file for a page:
1
2
3
export default {
middleware: 'auth'
}
  • Global, add to nuxt.config.js:
1
2
3
router: {
middleware: ['auth']
}

To bypass auth for some route, add to .vue file for a page:

1
2
3
export default {
auth: false
}

To redirect to / instead of stay in the url after a successful login, add this to .vue for a page:

1
2
3
export default {
auth: 'guest'
}
  1. Scheme
  • Schemes define authentication logic.
  • Strategy is a scheme instance.
  • Multiple strategies can be applied to a nuxt app.

Here’s the config for local and github strategy in nuxt.config.js:

1
2
3
4
5
6
auth: {
strategies: {
local: { /* ... */ },
github: { /* ... */ },
}
}

Here we only consider local scheme.

  • Local scheme is crendentials/token based for flows like ‘JWT’.
  • Local scheme is enabled, preconfigured and default. Can be turned off by setting strategies.local: false.

Config in nuxt.config.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
auth: {
strategies: {
local: {
token: {
property: 'token',
global: true
},
user: {
property: 'user'
},
endpoints: {
login: { url: '/login', method: 'post'},
// logout: { url: '/api/auth/logut', method: 'post' },
logout: false, // set it to false to disable logout and just do it locally.
user: { url: '/me', method: 'get' }
}
}
}
}

Next, add index.js in store folder to activate vuex store.

Author

Chendongtian

Posted on

2022-10-24

Updated on

2022-11-24

Licensed under

Comments